mongodb - 在嵌套数组 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
不会显示contentId
sceneId
解决方案
您可以使用此聚合查询:
$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
}
}
])
这里的例子
推荐阅读
- android - 在 Android Studio 中克隆项目时如何更新 build.gradle 脚本名称?
- python - 在 apache 超集的 app.py 日志记录配置器中获取 KeyError
- svelte - Svelte(套件)中的预渲染样式
- php - PHP Docusign API - 收到第二个签名请求时,自定义选项卡中的换行符消失
- python - MySQL JSON 查询发送随机数
- java - 仅在 QA 环境中而不是在本地获取“java.lang.NoClassDefFoundError:无法初始化类”?
- angular - Angular8 - 成功发布请求后重定向页面
- java - Flutter:如何在 Apple M1 芯片中安装 Flutter 及其所需的 SDK 元素?
- javascript - 使用 javascript/reactjs 从 MS 团队获取我的用户名
- mysql - 使用docker时mysql数据库保存在哪里?