Mongodb 查找数组中某个属性为空的所有条目
我有以下mongodb查询:Mongodb 查找数组中某个属性为空的所有条目,mongodb,Mongodb,我有以下mongodb查询: db .getCollection("entries") .find({ $and: [ { "array.attribute_1": { $exists: true, $not: { $size: 0 } } }, { $or: [ { "array.attribute_
db
.getCollection("entries")
.find({
$and: [
{
"array.attribute_1": {
$exists: true,
$not: {
$size: 0
}
}
},
{
$or: [
{ "array.attribute_2": { $exists: true, $size: 0 } },
{ "array.attribute_2": { $exists: true, $eq: {} } }
]
},
]
})
以及我的文档的示例:
{
_id: 'foo',
array: [
{attribute_1: [], attribute_2: []},
{attribute_1: ['bar'], attribute_2: []}
]
}
根据我的理解,我的查询应该找到所有条目
,这些条目在数组
中至少有一个元素,该元素存在且不为空属性_1
和存在的空数组或空对象属性_2
。但是,此查询将查找所有条目
,这些条目在数组
中包含所有元素,这些元素存在且不为空属性_1
和存在的空数组或空对象属性_2
。因此,将找不到我的foo
条目
对于我的要求,正确的公式应该是什么?
$find
将找到符合匹配条件的第一个文档,在您的情况下,第一个文档包含所有数组。您需要将$project
与$filter
一起使用,或者将聚合与$unwind
和$match
一起使用
大概是这样的:
db.collection.aggregate([
{ $unwind: "$array" },
{
$match: {
$and: [
{ "array.attribute_1.0": { $exists: true }},
{
$or: [
{ "array.attribute_2.0": { $exists: false } },
{ "array.attribute_2.0": { $eq: {} } }
]
}
]
}
}
])
你可以看到它在工作
另外,由于您正在尝试使用
.0
和$exists
来确定数组是否为空并且是否同时存在,因此,使用$exists
和$size
可以快速且简单地获得相同的结果 不幸的是,.0
不起作用,因为属性_2
可以是一个对象,但感谢您提醒我注意$unwind
,因为它正是需要的