Mongo DB对象数组在另一个集合上的查找

时间:2020-05-07 17:01:43

标签: node.js database mongodb express

所以问题是我的Posts集合的每个文档(注释字段)中都有一个对象数组。每个对象都有一个属性“ commentAuthorId”。我不愿做的事情是对注释数组中的每个对象执行查找,并根据“ commentAuthorId”前面提到的内容,将有关注释作者的信息插入到该对象中。用户信息位于另一个称为“用户”的集合中。 这是我到目前为止尝试过的,但是没有用。

    {
      $unwind: '$comments'
    },
    {
      $lookup: {
        from: "Users",
        localField: "comments.commentAuthorId",
        foreignField: "_id",
        as: "commentAuthorDetails",
      },
    },
    {$group: {  
      _id: "$_id",
      comments: {
        $push: {
            _id: "$comments._id",
            authorDetails: "$commentAuthorDetails"
        }
      }
    }

文档示例-帖子:

 {
   "_id":{
      "$oid":"5eb2ed9f4c53d52b8c69f01b"
   },
   "createdBy":"5e45bf41e2465801801455d9",
   "postContent":"dasdsa\n#lazyloadingtest\n      ",
   "tags":[
      "lazyloadingtest"
   ],
   "addedAt":{
      "$date":"2020-05-06T17:02:23.138Z"
   },
   "likes":[

   ],
   "likesCount":0,
   "comments":[
      {
         "content":"afdsfsdf",
         "author":"Kacper",
         "postId":"5eb2ed9f4c53d52b8c69f01b",
         "commentAuthorId":"5e45bf41e2465801801455d9",
         "addedAt":{
            "$date":"2020-05-06T17:02:25.167Z"
         },
         "_id":{
            "$oid":"5eb2eda14c53d52b8c69f01c"
         }
      }
   ]
}

文档示例-用户:

{
   "_id":{
      "$oid":"5e45bf41e2465801801455d9"
   },
   "name":"Kacper",
   "email":"kacper@kacper.pl",
   "password":"$2b$12$QeCw0AKlRI1kjAJc6eM5hOvxc5gRk/FhuI9vDcGLitsrSkHQZp8ky",
   "userPicture":null
}

预期的查询聚合结果:

{
  "_id":{
     "$oid":"5eb2ed9f4c53d52b8c69f01b"
  },
  "createdBy":"5e45bf41e2465801801455d9",
  "postContent":"dasdsa\n#lazyloadingtest\n      ",
  "tags":[
     "lazyloadingtest"
  ],
  "addedAt":{
     "$date":"2020-05-06T17:02:23.138Z"
  },
  "likes":[

  ],
  "likesCount":0,
  "comments":[
     {
        "content":"afdsfsdf",
        "author":"Kacper",
        "postId":"5eb2ed9f4c53d52b8c69f01b",
        "commentAuthorId":"5e45bf41e2465801801455d9",
        "addedAt":{
           "$date":"2020-05-06T17:02:25.167Z"
        },
        "_id":{
           "$oid":"5eb2eda14c53d52b8c69f01c"
        },
        "postAuthorInfo": {
          "_id":{
             "$oid":"5e45bf41e2465801801455d9"
          },
          "name":"Kacper",
          "email":"kacper@kacper.pl",
          "password":"$2b$12$QeCw0AKlRI1kjAJc6eM5hOvxc5gRk/FhuI9vDcGLitsrSkHQZp8ky",
          "userPicture":null
       }
     }
  ]
}

只有一个注释,但是我不想对基于“ commentAuthorId”字段的每个下一个注释进行此查找。

0 个答案:

没有答案
相关问题