mongodb - 查找数组内的所有文档 - MongoDB 聚合
问题描述
我需要对数组内的所有文档执行查找阶段。
收藏:
{
{
"name": "test",
"age": 2,
"replies": [
{
"title": "testtt",
"merta_id": 1
},
{
"title": "testiona",
"merta_id": 5
},
{
"title": "the thirth test",
"merta_id": 4
}
]
}
}
mertas
收藏:
{
{
_id: 1,
a: "aaaa",
b: "bbbb"
},
{
_id: 5,
a: "AaAA",
b: "BbbB"
},
{
_id: 4,
a: "Aou",
b: "Boo"
}
}
预期输出:
{
{
"name": "test",
"age": 2,
"replies": [
{
"title": "testtt",
"merta_id": 1,
"merta": {
_id: 1,
a: "aaaa",
b: "bbbb"
}
},
{
"title": "testiona",
"merta_id": 5,
"merta": {
_id: 5,
a: "aaaa",
b: "bbbb"
}
},
{
"title": "the thirth test",
"merta_id": 4
"merta":{
_id: 4,
a: "Aou",
b: "Boo"
}
}
]
}
}
我需要一个聚合阶段来对“回复”上的所有文档执行查找并添加一个新merta
字段,该字段应该从mertas
集合中查找。我尝试使用$map
阶段,但收到错误“无法识别的管道阶段名称:'$lookup'”
解决方案
您可以使用以下聚合
db.collection.aggregate([
{ "$unwind": "$replies" },
{ "$lookup": {
"from": "mertas",
"localField": "replies.merta_id",
"foreignField": "_id",
"as": "replies.merta"
}},
{ "$unwind": "$replies.merta" },
{ "$group": {
"_id": "$_id",
"data": { "$first": "$$ROOT" },
"replies": { "$push": "$replies" }
}},
{ "$replaceRoot": {
"newRoot": {
"$mergeObjects": ["$data", { "replies": "$replies" }]
}
}}
])
推荐阅读
- android - 带有 Github Actions 和 Fastlane 的 Android CI/CD
- javascript - 尝试部署不和谐机器人时出错
- android - 当viewmodel持有来自客户端的价值时,如何阻止观察者被多次触发?
- javascript - 是否有用于编辑谷歌工作表单元格的循环功能?
- nginx - nginx proxy_pass 使用具有动态 IP 地址的主机
- php - 为 Laravel 的 Eloquent 中的每个 id 选择最后一行
- android - 将 Android Studio 3.0.2 更新到 3.6.1 后项目文件夹丢失,如何恢复?
- php - Symfony - 在 Sylius 存储库中获取 security.token_storage
- bash - 无法访问 colab 中的文件
- java - 使用 selenium - 我无法登录 https://passport.amazon.work