【发布时间】:2019-10-14 06:34:07
【问题描述】:
如果子数组文档不满足 mongoose 中的匹配条件,Mongoose 不会返回对象。
MongoDB 查询:
db.fruits.aggregate(
{ $match: { "isActive": true, fruitId: "kipld" } },
{ $unwind: '$types' },
{ $match: { "types.isActive": true } },
{ $group: {
_id: '$_id',
name: {$first: '$name'},
price: { $first: '$price' },
types : { $push : '$types' }
}
},
{ $project: {
'_id': 1,
'name':1,
'price': 1,
'types': 1,
}
}
)
MongoDB 集合:
{
_id: "abcdefg",
fruitId: "kipld",
isActive: true,
types :[
{
name: "Kashmir Apple",
price: 90,
isActive: false
},
{
name: "American Apple",
price: 120,
isActive: false
}
]
}
预期结果如下:
{
_id: "abcdefg",
fruitId: "kipld",
isActive: true,
types :[]
}
但是当我运行上述查询时,我什么也没得到。
【问题讨论】:
-
您的查询显示
{ $match: { "types.isActive": true } },但输入文档的"tyoes.isActive"值为false。因此,没有选择任何文档。 -
这是预期的行为。
-
如果不存在
true记录,我可以这样做以返回EMPTY数组吗? -
@Rajath 你可以。但是,与您正在使用的查询管道无关。