2

文档的架构

id是加入的关键

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

目标

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

1 回答 1

0

您可以在架构上使用 $lookup 并在 $unwind 和 $project 的帮助下获得所需的结果。

询问:

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

输出:

[
  {
    "properties": {
      "_id": ObjectId("5a934e000102030405000000"),
      "id": 1,
      "metadata": "abc"
    }
  },
  {
    "properties": {
      "_id": ObjectId("5a934e000102030405000001"),
      "id": 2,
      "metadata": "def"
    }
  }
]
于 2021-03-19T13:25:16.333 回答