$ lookup并推送新数据

时间:2018-01-21 06:02:42

标签: mongodb mongodb-query aggregation-framework

您好我有一个讨论对象集合和一个用户deatils集合。

讨论集合将参与者用户名存储在字符串数组中。 讨论集如下:

       [{ "_id": "5a4dbdaab46b426863e7ead3",
        "topic": "test",
        "topicDesc": "test123",
        "createdOn": "2018-01-04T05:37:46.088Z",
        "participants": ["akhil","ben"]  //[usernames]
      }]

用户详细信息收集如下:

[{
   "_id": "59e6d6ba02e11e1814481022",
   "username": "ben",
   "name": "Ben S",
   "email": "qwerty@123.com",
},{
   "_id": "5a0431b1d6fab00cdf484677",
   "username": "akhil",
   "name": "Akhil Clement",
   "email": "qwerty@123.com",
}]

和结果JSON就像

[{ "_id": "5a4dbdaab46b426863e7ead3",
        "topic": "test",
        "topicDesc": "test123",
        "createdOn": "2018-01-04T05:37:46.088Z",
        "participants": ["akhil","ben"]  //[usernames]
        "participantDetails": [{
              "_id": "59e6d6ba02e11e1814481022",
              "username": "ben",
              "name": "Ben S",
              "email": "qwerty@123.com",
            },{
              "_id": "5a0431b1d6fab00cdf484677",
              "username": "akhil",
              "name": "Akhil Clement",
              "email": "qwerty@123.com",
        }]
      }]

1 个答案:

答案 0 :(得分:1)

您需要$lookup使用用户集和$group

 db.dis.aggregate(
    [
        {$unwind : "$participants"},
        {$lookup : {from : "us", localField : "participants", foreignField : "username", as : "userData"}}, 
        {$group : {_id : {
            _id : "$_id", topic : "$topic", topicDesc : "$topicDesc", createdOn : "$createdOn" 
         }, 
         participants : {$push :  "$participants" } ,  
         participantDetails : {$push : {$arrayElemAt : ["$userData", 0]}}}
         },
         {$project : {
            _id : "$_id._id", 
            topic : "$_id.topic", 
            topicDesc : "$_id.topicDesc", 
            createdOn : "$_id.createdOn",
            participants : 1 ,  
            participantDetails : 1
         }}
    ]
).pretty()

结果

{
    "participants" : [
        "akhil",
        "ben"
    ],
    "participantDetails" : [
        {
            "_id" : "59e6d6ba02e11e1814481020",
            "username" : "akhil",
            "name" : "Akhil Clement",
            "email" : "qwerty@123.com"
        },
        {
            "_id" : "59e6d6ba02e11e1814481021",
            "username" : "ben",
            "name" : "Ben S",
            "email" : "qwerty@123.com"
        }
    ],
    "_id" : "5a4dbdaab46b426863e7ead3",
    "topic" : "test",
    "topicDesc" : "test123",
    "createdOn" : "2018-01-04T05:37:46.088Z"
}

修改

$push更改为$addToSet以避免重复