如何正确查找 mongodb 中的多个字段?
How to properly lookup for several fields in mongodb?
假设我有 2 个 collections
// Post collection:
{
"_id": "61f7a933b209737de4cc2657",
"author": "61d30188cf93e83e08d14112",
"title": "Some title",
"createts": 1643620659355
}
// User collection:
{
"_id": "61d30188cf93e83e08d14112",
"nickname": "Bob",
"link": "bobspage"
}
我需要得到这个结果
{
"_id": "61f7a933b209737de4cc2657",
"author": {
"_id": "61d30188cf93e83e08d14112",
"nickname": "Bob",
"link": "bobspage"
},
"title": "Some title",
"createts": 1643620659355
}
我如何使用 聚合 发出请求,这将显示此输出?
只需在聚合查询中使用$lookup
:
- 首先
$lookup
,它生成一个名为 author
的字段,它是一个包含所有值的数组。
- 要获取
author
作为对象,请使用 $arrayElemAt
. 获取数组的第一个结果
db.post.aggregate([
{
"$lookup": {
"from": "user",
"localField": "author",
"foreignField": "_id",
"as": "author"
}
},
{
"$addFields": {
"author": {
"$arrayElemAt": [
"$author",
0
]
}
}
}
])
示例here
假设我有 2 个 collections
// Post collection:
{
"_id": "61f7a933b209737de4cc2657",
"author": "61d30188cf93e83e08d14112",
"title": "Some title",
"createts": 1643620659355
}
// User collection:
{
"_id": "61d30188cf93e83e08d14112",
"nickname": "Bob",
"link": "bobspage"
}
我需要得到这个结果
{
"_id": "61f7a933b209737de4cc2657",
"author": {
"_id": "61d30188cf93e83e08d14112",
"nickname": "Bob",
"link": "bobspage"
},
"title": "Some title",
"createts": 1643620659355
}
我如何使用 聚合 发出请求,这将显示此输出?
只需在聚合查询中使用$lookup
:
- 首先
$lookup
,它生成一个名为author
的字段,它是一个包含所有值的数组。 - 要获取
author
作为对象,请使用$arrayElemAt
. 获取数组的第一个结果
db.post.aggregate([
{
"$lookup": {
"from": "user",
"localField": "author",
"foreignField": "_id",
"as": "author"
}
},
{
"$addFields": {
"author": {
"$arrayElemAt": [
"$author",
0
]
}
}
}
])
示例here