Search code examples
c#mongodbjoinaggregation-frameworkmongodb-.net-driver

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


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?


Solution

  • 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.