Search code examples
arraysmongodbaggregationnested-documents

Merge two objects inside an array, one with a key nested deeper than the other in the same document in Mongo DB


Schema of the document

id is the key to join

{ 
    "foo" : [
        {
            "properties" : {
                "id" : 1
            }, 
        }, 
        {
            "properties" : {
                "id" : 2
            }, 
        }], 
    "bar" : [
        {
            "id" : 1,
            "metadata" : abc 
        },
        {
            "id" : 2,
            "metadata" : def 
        }
    ]
}

Goal

 { 
    "foo" : [
        {
            "properties" : {
                "id" : 1,
                "metadata" : abc 
            }, 
        }, 
        {
            "properties" : {
                "id" : 2,
                "metadata" : def 
            }, 
        }, 
}

Solution

  • You can use the $lookup on the schema and with the help of $unwind and $project you will get the desired result.

    Query:

    db.foo.aggregate({
      $lookup: {
        from: "bar",
        localField: "properties.id",
        foreignField: "id",
        as: "properties"
      },
      
    },
    {
      $unwind: {
        path: "$properties",
        
      }
    },
    {
      $project: {
        _id: 0,
        properties: 1
      }
    })
    

    Output:

    [
      {
        "properties": {
          "_id": ObjectId("5a934e000102030405000000"),
          "id": 1,
          "metadata": "abc"
        }
      },
      {
        "properties": {
          "_id": ObjectId("5a934e000102030405000001"),
          "id": 2,
          "metadata": "def"
        }
      }
    ]