我有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
的{{1}}中添加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")
}
答案 0 :(得分:0)
您可以$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()