首页 > 解决方案 > 在嵌套数组 MongoDB 中加入文档

问题描述

我的第一个集合,称为Scenes如下所示:

{
  sceneId: "id1",
  contentId: "contentId1",
  comments: [{
    comment: "abc",
    userId: "test1"
  },
  {
    comment: "def",
    userId: "test2"
  }]
},
{
  sceneId: "id2",
  contentId: "contentId2",
  comments: [{
    comment: "abc",
    userId: "test1"
  },
  {
    comment: "def",
    userId: "test2"
  }]
}

我的任何第二个集合,称为Userdatas,看起来像这样:

{
  userId: "test1",
  profilPicture: "def.jpg"
},
{
  userId: "test2",
  profilPicture: "abc.jpg"
}

我想以某种方式加入他们,我得到以下信息:

{
  sceneId: "id1",
  contentId: "contentId1",
  comments: [{
    comment: "abc",
    userId: "test1",
    profilPicture: "def.jpg"
  },
  {
    comment: "def",
    userId: "test2",
    profilPicture: "abc.jpg"
  }]
},
{
  sceneId: "id2",
  contentId: "contentId2",
  comments: [{
    comment: "abc",
    userId: "test1",
    profilPicture: "def.jpg"
  },
  {
    comment: "def",
    userId: "test2",
    profilPicture: "abc.jpg"
  }]
}

而且我不知道该怎么做,我以前的所有尝试都失败了。帮助表示赞赏!关键问题是,操作员在通过分组时$group不会显示contentIdsceneId

标签: mongodbmongoosemongodb-query

解决方案


您可以使用此聚合查询:

  • $unwind comments要解构和加入的第一个数组comments.userId
  • 然后$lookup这就像一个 JOIN,userId在集合之间合并 s,生成一个名为 的对象data
  • 解构$data以获取值。
  • 使用 .添加profilPicture到对象comments$set
  • $group通过sceneId将所有内容添加comments到数组中。
  • 并用于$projection 仅显示您想要的字段。
db.Scenes.aggregate([
  {
    "$unwind": "$comments"
  },
  {
    "$lookup": {
      "from": "Userdatas",
      "localField": "comments.userId",
      "foreignField": "userId",
      "as": "data"
    }
  },
  {
    "$unwind": "$data"
  },
  {
    "$set": {
      "comments.profilPicture": "$data.profilPicture"
    }
  },
  {
    "$group": {
      "_id": "$sceneId",
      "comments": {
        "$push": "$comments"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "sceneId": "$_id",
      "comments": 1
    }
  }
])

这里的例子


推荐阅读