本文介绍了$ lookup并推送新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个讨论对象集合,一个用户死亡集合.

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": "[email protected]",
},{
   "_id": "5a0431b1d6fab00cdf484677",
   "username": "akhil",
   "name": "Akhil Clement",
   "email": "[email protected]",
}]

结果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": "[email protected]",
            },{
              "_id": "5a0431b1d6fab00cdf484677",
              "username": "akhil",
              "name": "Akhil Clement",
              "email": "[email protected]",
        }]
      }]

推荐答案

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

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

结果

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

编辑

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

这篇关于$ lookup并推送新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 18:40