【发布时间】:2021-11-09 13:36:47
【问题描述】:
这里有两个收藏。
我想通过执行$group 聚合或任何其他方法在数组中获取发布者详细信息。
书籍
[
{
"_id":8751,
"title":"The Banquet",
"author":"AB",
"copies":2,
"publisher":[
1,
2
]
},
{
"_id":8752,
"title":"Divine Comedy",
"author":"Dante",
"copies":1,
"publisher":[
3,
1
]
}
]
出版商
[
{
"id":1,
"name":"p 1"
},
{
"id":2,
"name":"p 2"
},
{
"id":3,
"name":"p 3"
},
{
"id":4,
"name":"p 4"
}
]
我已尝试使用以下查询,但结果不是预期的。
db.books.aggregate([
{
"$unwind": "$publisher"
},
{
"$group": {
"_id": "$publisher",
}
},
{
"$lookup": {
"from": "publisher",
"localField": "_id",
"foreignField": "id",
"as": "publishers"
}
}
])
预期输出
[
{
"id":1,
"name":"p 1"
},
{
"id":2,
"name":"p 2"
},
{
"id":3,
"name":"p 3"
}
]
如何获取数组中的出版商列表
【问题讨论】:
-
你是什么意思出版商列表中的书籍?在预期的输出中没有数组。您可以将数组字段与单个字段连接,如果数组包含该元素,它们将匹配。
标签: mongodb mongoose mongodb-query aggregation-framework