[英]MongoDB adding objectID from one collection to another
我有mongodb collection1
,如下所示
{
"_id" : ObjectId("5a7286c9bcf16750f621007b"),
"host" : "host1",
"column2" : "value2",
"column3" : 6,
"date_created" : "2015-01-25 00:00:00"
}
我有mongodb collection2
,如下所示
{
"_id" : ObjectId("5a728429bcf16750f62056e8"),
"hostname" : "host1",
"column2" : 322,
"column3" : 81,
}
{
"_id" : ObjectId("5a728429cde16750f62056e8"),
"hostname" : "host1",
"column2" : 312,
"column3" : 89,
}
我想補充field
在collection2
命名為collection1_id
,使得hostname
在collection2
匹配host
在collection1
我的輸出應該如下
{
"_id" : ObjectId("5a728429bcf16750f62056e8"),
"hostname" : "host1",
"column2" : 322,
"column3" : 81,
"collection1_id" : ObjectId("5a7286c9bcf16750f621007b")
}
{
"_id" : ObjectId("5a728429cde16750f62056e8"),
"hostname" : "host1",
"column2" : 312,
"column3" : 89,
"collection1_id" : ObjectId("5a7286c9bcf16750f621007b")
}
我現在所知道的是我將需要運行db.collection2.update()
您可以使用聚合管道$lookup
並使用結果光標更新collection2中的_id
管道
db.co2.aggregate(
[
{$lookup : {from : "co1", localField : "hostname", foreignField : "host", as : "collection1_id"}},
{$addFields : {collection1_id : {$arrayElemAt : ["$collection1_id._id" , 0]}}}
]
).pretty()
結果
> db.co2.aggregate([{$lookup : {from : "co1", localField : "hostname", foreignField : "host", as : "collection1_id"}},{$addFields : {collection1_id : {$arrayElemAt : ["$collection1_id._id" , 0]}}}]).pretty()
{
"_id" : ObjectId("5a728429bcf16750f62056e8"),
"hostname" : "host1",
"column2" : 322,
"column3" : 81,
"collection1_id" : ObjectId("5a7286c9bcf16750f621007b")
}
{
"_id" : ObjectId("5a728429cde16750f62056e8"),
"hostname" : "host1",
"column2" : 312,
"column3" : 89,
"collection1_id" : ObjectId("5a7286c9bcf16750f621007b")
}
>
編輯
適用於mongo 3.4及更低版本
用$project
代替$addFields
db.co2.aggregate(
[
{$lookup : {from : "co1", localField : "hostname", foreignField : "host", as : "collection1_id"}},
{$project : {hostname : 1, column2 : 1, column3 : 1, collection1_id : {$arrayElemAt : ["$collection1_id._id" , 0]}}}
]
).pretty()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.