Search code examples
mongodbmongodb-.net-driver

MongoDb - Data from Foreign Key Table in One Call


Let's say I have two collections in MongoDb:

  1. Items (int64 id, string description, int64(Sheves FK) homeShelf)
  2. and Shelves(int64 id, string description)

Is it somehow possible for me to get the shelf description of the item while getting an Item document in one call? Preferably via the C# driver.

I am guessing the answer is no, but since things like Entity Framework have the functionality, I figured I would ask.


Solution

  • If you are using MongoDB 3.2+, you can use the $lookup operator with the aggregation.

    Items

    { 
        "_id" : NumberLong(1), 
        "description" : "Item Description", 
        "homeShelf" : NumberLong(1000)
    }
    

    Shelves

    { 
        "_id" : NumberLong(1000), 
        "Description" : "Shelf Description"
    }
    

    Aggregation Query

    db.Items.aggregate(
      [
        {
          $lookup: {
              "from" : "Shelves",
              "localField" : "homeShelf",
              "foreignField" : "_id",
              "as" : "Shelves"
          }
        }
      ]
    );
    

    Result

    { 
        "_id" : NumberLong(1), 
        "description" : "Item Description", 
        "homeShelf" : NumberLong(1000), 
        "Shelves" : [
            {
                "_id" : NumberLong(1000), 
                "Description" : "Shelf Description"
            }
        ]
    }
    

    You can use the following code in C# Driver. Add match and project stages as you need:

    var items = itemsCollection.Aggregate()
        .Lookup("Shelves", "homeShelf", "_id", "Shelves").ToList();