简体   繁体   中英

How to join a collection inside an array of objects in MongoDB

I have document like this in a collection called notifications

[
   {
       _id: 4f6a686ad4821115c0b4a721,
       title: "title 1"
       comments: [
         {
           comment: 'test 1',
           client_id: '1664158590921',
           createdAt: 2020-09-22T20:00:00.000Z
         },
         {
           comment: 'test 2',
           client_id: '1664158590875',
           createdAt: 2020-09-22T20:00:00.000Z
         }
       ]
   }
]

I have document like this in a collection called clients

{
    _id: 5f6a651faf591a3c742016dd,
    client_id: '1664158590921',
    email: 'test1@gmail.com'
}
{
    _id: 5f6a651faf591a3c742016dd,
    client_id: '1664158590875',
    email: 'test2@gmail.com'
}

I am trying to create a mongodb query to get a result like this:

[
    {
       _id: 4f6a686ad4821115c0b4a721,
       title: "title 1"
       comments: [
         {
             comment: 'test 1',
             client_id: {
                _id: 5f6a651faf591a3c742016dd,
                client_id: '1664158590921',
                email: 'test1@gmail.com'
             },
             createdAt: 2020-09-22T20:00:00.000Z
         },
         {
             comment: 'test 2',
             client_id: {
                _id: 5f6a651faf591a3c742016dd,
                client_id: '1664158590875',
                email: 'test2@gmail.com'
             },
             createdAt: 2020-09-22T20:00:00.000Z
         }
      ]
   }
]

Is it possible or not? Any advice on how to approach a similar result like this is much appreciated, thanks

  1. Since the localField is an array, first you have to $unwind it.(required for next stage)
  2. use $lookup for matching.
  3. Group them by _id and cleanup the output.

The solution should be something like this.

db.notifications.aggregate([
   {
      "$unwind":"$comments"
   },
   {
      "$lookup":{
         "from":"clients",
         "localField":"comments.client_id",
         "foreignField":"client_id",
         "as":"client_id"
      }
   },
   {
      "$group":{
         "_id":"$_id",
         "title":{
            "$first":"$title"
         },
         "comments":{
            "$push":{
               "comment":"$comments.comment",
               "client_id":"$client_id",
               "createdAt":"$comments.createdAt"
            }
         }
      }
   }
]).pretty()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM