我的数据库集合中有一个以下对象结构:
{
"name" : "test",
"code" : "test",
"attributes" : [
{
"name" : "test1",
"code" : "code1"
},
{
"name" : "test2",
"code" : "code2",
"value" : true
},
{
"name" : "test3",
"code" : "code3",
"value" : ""
},
{
"name" : "test4",
"code" : "code4"
"value" : [
{
"code" : "code4.1",
"name" : "test4.1"
},
{
"name" : "test4.2"
}
]
}
]
}
所以“value”属性可以是空字符串、 bool 值、数组,甚至根本没有定义。
如何进行查询以列出具有非空属性数组并且没有在数组中的至少一个对象中定义“attributes.value”属性的对象?
附言我尝试了以下查询:
db.collection.find({"attributes": {$exists: true, $ne: []}, "attributes.value": {$exists: false}})
但查询结果为空。
最佳答案
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
这个查询对我有用:
db.getCollection('testeur').find({ "attributes": {
$exists: true,
$ne: [],
$elemMatch: { "value": {$exists: false } }
}
})
关于arrays - MongoDB 对象属性 $ 存在于嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505816/