文档的架构
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
},
},
}
您可以在架构上使用$lookup,在$unvent和$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"
}
}
]