Mongo db c# driver - how to join by id in collection?

拥有回忆 提交于 2020-07-04 19:53:39

问题


I'm using Mongo DB c# driver 2, I'm trying to join 2 collections by ID (Many to Many)

Class A
{
   public string id;
   public string name;
   public list<string> classBReferenceid; // <--- I want use this as the "keys" for the join
   public list<B> myBs;
}
Class B
{
   public string id; // <--- I use this as the "key" for the join
   public string name;
}

In my DB class "A" is saved without the data of "myBs" and I want to pull it from mongo in one call.

I tried to use the Lookup function:

IMongoCollection<A> mongoACollection = // already set in driver....
IMongoCollection<B> mongoBCollection = // already set in driver....

IAggregateFluent<A> results = _mongoACollection.Aggregate().
                Lookup<A, B, A>(
                    mongoBCollection,
                    a => a.classBReferenceid,
                    b => b.Id,
                    a => a.myBs);

But it doesn't work (doesn't join anything) probably because the "classBReference" is a list and not an "id".

How can I use the Lookup to join a collection by id that appears in a list of id's in another collection?


回答1:


This feature was introduced in MongoDb v3.3.4, but my local instance was using MongoDb 3.2 via Mongo2Go, which I use for unit tests.

Once I upgraded my local instance to v3.3.4, the issue was solved.



来源:https://stackoverflow.com/questions/44944711/mongo-db-c-sharp-driver-how-to-join-by-id-in-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!