使用聚合在我的个人资料集合中添加用户ID

时间:2016-12-12 06:47:38

标签: mongodb mongodb-query aggregation-framework robo3t

以下是我的用户收集数据

用户集合

{
    "_id" : ObjectId("584bc9ba420a6b189c510af6"),
    "old_user_id" :1,
    "name" :"aaa"
},
{
    "_id" : ObjectId("9ba420a584bc6b189c59ba42"),
    "old_user_id" : 2,
     "name" :"bbb"
},
{
    "_id" : ObjectId("59ba4284bc0a6b189c3323w23"),
    "old_user_id" : 3,
    "name" :"ccc"
}

myprofile collection

{        
    "old_user_id" :1,
    "name" :"aaa",
    "number":"123456789"
},
{
    "old_user_id" : 2,
     "name" :"bbb",
     "number":"678912345"
},
{
    "old_user_id" : 3,
    "name" :"ccc",
    "number":"673458912"    
},
{

    "old_user_id" : 2,
    "name" : "bbb",
    "adress" : "afsfdidhddk"
}   

我的期望:

我需要在两个集合中匹配old_user_id并更新user集合' _id'在我的profile集合

{
    "userid":"584bc9ba420a6b189c510af6",
    "old_user_id" :1,
    "name" :"aaa",
    "number":"123456789"
},
{
    "userid":"9ba420a584bc6b189c59ba42",
    "old_user_id" : 2,
     "name" :"bbb",
     "number":"678912345"
},
{
    "userid":"59ba4284bc0a6b189c3323w23",
    "old_user_id" : 3,
    "name" :"ccc",
    "number":"673458912"
},
    {

    "old_user_id" : 2,
    "name" : "bbb",
    "adress" : "afsfdidhddk"
    "userid" : "9ba420a584bc6b189c59ba42"
}

2 个答案:

答案 0 :(得分:2)

您可以使用mongo聚合。使用$ lookup,$ project和$ unwind将有所帮助。 我已经制定了查询,希望这会有所帮助:

body

答案 1 :(得分:1)

<强>更新

db.user.find().forEach(function (user) {

    var cursor = db.myprofile.find({"old_user_id":  user.old_user_id});

    cursor.forEach(function(myprofile) {
        myprofile.userid = user._id.str;
        db.myprofile.save(myprofile);
    });
});

结果:

db.myprofile.find().pretty()

   {
    "_id" : ObjectId("584e7294678ae15db4fab039"),
    "old_user_id" : 1,
    "name" : "aaa",
    "number" : "123456789",
    "userid" : "584e7294678ae15db4fab035"
}
{
    "_id" : ObjectId("584e7294678ae15db4fab03a"),
    "old_user_id" : 2,
    "name" : "bbb",
    "number" : "678912345",
    "userid" : "584e7294678ae15db4fab036"
}
{
    "_id" : ObjectId("584e7294678ae15db4fab03b"),
    "old_user_id" : 3,
    "name" : "ccc",
    "number" : "673458912",
    "userid" : "584e7294678ae15db4fab037"
}
{
    "_id" : ObjectId("584e7294678ae15db4fab03c"),
    "old_user_id" : 2,
    "name" : "bbb",
    "adress" : "afsfdidhddk",
    "userid" : "584e7294678ae15db4fab036"
}

注意:_id fiels仍会显示在生成的文档中,但您应该能够使用它。是MongoDB的默认行为。您可以创建一个没有索引_id字段like in here: db.createCollection("user", { autoIndexId: false })

的集合