Get info from another collection based of _id and merge - MongoDB

I have two collections. Lets call one baskets and the other one fruits.

In baskets we have the following document:

[{
    basket_name: "John's Basket",
    items_in_basket: [
        {
            fruit_id: 1,
            comment: "Delicious!"
        },
        {
            fruit_id: 2,
            comment: "I did not like this"
        }
    ]
}]

And in fruits we have the following documents:

[{
    _id: 1,
    fruit_name: "Strawberry",
    color: "Red"
},
{
    _id: 2,
    fruit_name: "Watermelon",
    color: "Green"
}]

How do I get information on each fruit in John's Basket?

The result should look like this:

[{
    fruit_id: 1,
    comment: "Delicious!",
    fruit_name: "Strawberry",
    color: "Red"
},
{
    fruit_id: 2,
    comment: "I did not like this",
    fruit_name: "Watermelon",
    color: "Green"  
}]

There's no "join" in MongoDB. You either could:

  • consider using a MapReduce function to create a new structure that contains the merged data
  • write the code necessary to fetch each fruit instance on demand and merge it in your client code with a basket document.
  • denormalize the data and include the details for each fruit in the basket document. This poses it's own set of issues as data is duplicated and updates to a particular fruit would then need to be made to every usage in the collection.

Both have their pros and cons.

You might find this Q/A helpful, and also this documentation for MongoDB.