Node.js 如何在MongoDB中的对象数组中加入集合

Node.js 如何在MongoDB中的对象数组中加入集合,node.js,mongodb,express,mongodb-query,Node.js,Mongodb,Express,Mongodb Query,我在一个叫做通知的集合中有这样的文档 [ { _id: 4f6a686ad4821115c0b4a721, title: "title 1" comments: [ { comment: 'test 1', client_id: '1664158590921', createdAt: 2020-09-22T20:00:00.000Z

我在一个叫做通知的集合中有这样的文档

[
   {
       _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
         }
       ]
   }
]
我在一个叫做clients的集合中有这样的文档

{
    _id: 5f6a651faf591a3c742016dd,
    client_id: '1664158590921',
    email: 'test1@gmail.com'
}
{
    _id: 5f6a651faf591a3c742016dd,
    client_id: '1664158590875',
    email: 'test2@gmail.com'
}
我正在尝试创建mongodb查询,以获得如下结果:

[
    {
       _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
         }
      ]
   }
]
有没有可能? 任何关于如何获得类似结果的建议都将不胜感激,谢谢

  • 由于localField是一个数组,首先必须$unwind它。(下一阶段需要)
  • 使用$lookup进行匹配
  • 按_id对它们进行分组并清理输出
  • 解决方案应该是这样的

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