Mongodb选择JSON数组中所有JSON对象中存在密钥的文档

Mongodb选择JSON数组中所有JSON对象中存在密钥的文档,json,mongodb,Json,Mongodb,我在MongoDB中的文档具有以下JSON结构。如何编写查询来选择包含JSON数组“test”且该数组中的所有JSON对象都具有键“attr3”的文档 不能检索上述文档,因为它有JSON数组“test”,但最后一个对象没有“attr3”。您可以检查test的$size数组和test.att3的$size数组,如果两者相同,则所有数组元素都包含属性att3 {$expr: {$and:[ "$test", //exists {$gt: [{$size: "

我在MongoDB中的文档具有以下JSON结构。如何编写查询来选择包含JSON数组“test”且该数组中的所有JSON对象都具有键“attr3”的文档


不能检索上述文档,因为它有JSON数组“test”,但最后一个对象没有“attr3”。

您可以检查
test的
$size
数组和
test.att3的
$size
数组,如果两者相同,则所有数组元素都包含属性
att3

{$expr: 
    {$and:[
        "$test", //exists
        {$gt: [{$size: "$test"},0]}, //non empty
        {$eq:[{$size: "$test"},{$size: "$test.att3"}]} //att3 present in all
    ]}
}
收藏

> db.t66.find()
{ "_id" : ObjectId("5c47df42efd14747b5de90f8"), "test" : [ { "att3" : "sda" }, { "att3" : "gsfe" }, {  }, { "att3" : "" } ] }
{ "_id" : ObjectId("5c47dfbfefd14747b5de90f9"), "test" : [ { "att3" : "sda" }, { "att3" : "gsfe" }, { "att3" : "fewfw" }, { "att3" : "" } ] }
{ "_id" : ObjectId("5c47e0fbefd14747b5de90fa") }
发现

聚合

> db.t66.aggregate([{$match : {$expr : {$and: [{$gt : [{$size : {$ifNull : ["$test", []]}},0]},{$eq:[{$size : "$test"},{$size : "$test.att3"}]}]}}}])
{ "_id" : ObjectId("5c47dfbfefd14747b5de90f9"), "test" : [ { "att3" : "sda" }, { "att3" : "gsfe" }, { "att3" : "fewfw" }, { "att3" : "" } ] }
>
> db.t66.find({$expr : {$and: [{$gt : [{$size : {$ifNull : ["$test", []]}},0]},{$eq:[{$size : "$test"},{$size : "$test.att3"}]}]}})
{ "_id" : ObjectId("5c47dfbfefd14747b5de90f9"), "test" : [ { "att3" : "sda" }, { "att3" : "gsfe" }, { "att3" : "fewfw" }, { "att3" : "" } ] }
> db.t66.aggregate([{$match : {$expr : {$and: [{$gt : [{$size : {$ifNull : ["$test", []]}},0]},{$eq:[{$size : "$test"},{$size : "$test.att3"}]}]}}}])
{ "_id" : ObjectId("5c47dfbfefd14747b5de90f9"), "test" : [ { "att3" : "sda" }, { "att3" : "gsfe" }, { "att3" : "fewfw" }, { "att3" : "" } ] }
>