$lookup and push new data

我们两清 提交于 2019-12-13 03:42:07

问题


Hi i'm having a discussion object collection and a user deatils collection.

Discussion collection stores the participants username in an array of strings. Discussion collection is as follows:

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

The user details collection is as follows:

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

and result JSON be like

[{ "_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:


you need to $lookup with user collection and $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()

result

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

EDIT

change $push to $addToSet to avoid duplicates



来源:https://stackoverflow.com/questions/48364138/lookup-and-push-new-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!