如何在 MongoDB 中使用聚合查找数组中的对象?
How to lookup object in array with aggregation in MongoDB?
我正在使用 aggregate([...])
方法从 MongoDB 获取 select 文档,但我对 $lookup
有问题,我无法获得结果查询后引用字段 info
,它不起作用,因为它总是 return 空数组。我该如何解决这个问题?
我的 MongoSchema 配置:
const PostModel = new Schema({
...,
info: [
{
label: {
type: ObjectId,
ref: 'catalogs',
required: true
},
value: {
type: ObjectId,
ref: 'attributes',
required: true
}
}
],
...
})
我的执行聚合查询集合的代码:
const doc = await PostModel.aggregate([
{
"$lookup": {
"from": "catalogs",
"localField": "info.label",
"foreignField": "_id",
"as": "infoLabel"
}
},
{
"$lookup": {
"from": "attributes",
"localField": "info.value",
"foreignField": "_id",
"as": "infoValue"
}
},
{
"$project": {
info: {
label: '$infoLabel',
value: '$infoValue'
}
}
}
])
console.log(doc) // it always return empty array :(
您需要先展开信息,然后使用有效的查找查询
{ $unwind:"$info" },
{ $lookup:{ ... } }
我正在使用 aggregate([...])
方法从 MongoDB 获取 select 文档,但我对 $lookup
有问题,我无法获得结果查询后引用字段 info
,它不起作用,因为它总是 return 空数组。我该如何解决这个问题?
我的 MongoSchema 配置:
const PostModel = new Schema({
...,
info: [
{
label: {
type: ObjectId,
ref: 'catalogs',
required: true
},
value: {
type: ObjectId,
ref: 'attributes',
required: true
}
}
],
...
})
我的执行聚合查询集合的代码:
const doc = await PostModel.aggregate([
{
"$lookup": {
"from": "catalogs",
"localField": "info.label",
"foreignField": "_id",
"as": "infoLabel"
}
},
{
"$lookup": {
"from": "attributes",
"localField": "info.value",
"foreignField": "_id",
"as": "infoValue"
}
},
{
"$project": {
info: {
label: '$infoLabel',
value: '$infoValue'
}
}
}
])
console.log(doc) // it always return empty array :(
您需要先展开信息,然后使用有效的查找查询
{ $unwind:"$info" },
{ $lookup:{ ... } }