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

Add user id in my profile collection using aggregation

下面是我的用户collection数据

用户collection

{
    "_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"
}

我的个人资料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"
}   

我的期望:

我需要匹配 collection 中的 old_user_id 并更新 profile collection 中的 user collection '_id'

{
    "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"
}

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

db.myprofile.aggregate([
    {
      $lookup:
        {
          from: "user",
          localField: "old_user_id",
          foreignField: "old_user_id",
          as: "inventory_docs"
        }
   },
   { $project : { _id : "$inventory_docs._id",
                  old_user_id:"$old_user_id",
                 "name":"$name",
                 "number":"$number" } },
   {$unwind: "$_id"}
])

更新:

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 字段仍然出现在生成的文档中,但您应该能够接受它。是 MongoDB 的默认行为。您可以创建一个没有索引 _id 字段的集合 like in here: db.createCollection("user", { autoIndexId: false })