MongoDB将objectID从一个集合添加到另一个集合

时间:2018-02-01 03:55:52

标签: mongodb foreign-keys mongodb-query

我有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中的hostnamecollection2中的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") }

1 个答案:

答案 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()