【发布时间】:2019-01-21 21:32:29
【问题描述】:
我有一个名为“main”的文档(或集合,以最适合获得解决方案的为准):
{
"field1":"value1",
"objects":[ {"key":1}, {"key":2} ]
}
我有另一个名为“foreign”的集合,其中包含以下三个文档:
//document 1
{
"foreignKey":1,
"name": "Mike"
}
//document 2 {
"foreignKey":2,
"name": "Michael"
}
//document 3
{
"foreignKey":3,
"name": "Mick"
}
我希望合并的结果是:
//results
{
"field1":"value1",
"objects":[
{
"foreignKey":1,
"name": "Mike"
},
{
"foreignKey":2,
"name": "Michael"
}
]
}
我只在MongoDB 中找到了几乎可以完成此任务的示例,但它的示例只有一个值数组;但我有一个对象数组。
我不知道怎么翻译成Mongo-cxx。
为方便起见,我从MongoDB site 复制了以下示例
------------------------------------------------
//Consider a collection orders with the following //document:
({ "_id" : 1, "item" : "MON1003", "price" : 350, "quantity" : 2, "specs" :
[ "27 inch", "Retina display", "1920x1080" ], "type" : "Monitor" }
//Another collection inventory contains the following //documents:
{ "_id" : 1, "sku" : "MON1003", "type" : "Monitor", "instock" : 120,
"size" : "27 inch", "resolution" : "1920x1080" }
{ "_id" : 2, "sku" : "MON1012", "type" : "Monitor", "instock" : 85,
"size" : "23 inch", "resolution" : "1280x800" }
{ "_id" : 3, "sku" : "MON1031", "type" : "Monitor", "instock" : 60,
"size" : "23 inch", "display_type" : "LED" }
(
//The following aggregation operation performs a join //on documents in the orders collection which match a //particular element of the specs array to the size //field in the inventory collection.
db.orders.aggregate([
//stage
{
$unwind: "$specs"
},
//stage
{
$lookup:
{
from: "inventory",
localField: "specs",
foreignField: "size",
as: "inventory_docs"
}
},
//stage
{
$match: { "inventory_docs": { $ne: [] } }
}
])
//The operation returns the following document:
{
"_id" : 1,
"item" : "MON1003",
"price" : 350,
"quantity" : 2,
"specs" : "27 inch",
"type" : "Monitor",
"inventory_docs" : [
{
"_id" : 1,
"sku" : "MON1003",
"type" : "Monitor",
"instock" : 120,
"size" : "27 inch",
"resolution" : "1920x1080"
}
]
}
【问题讨论】:
标签: join aggregate lookup aggregation mongo-cxx-driver