Mongo+PHP查询如何检查字段是否为空

Mongo+PHP Query How to check if an field is empty

数据:

"field1" : { "sub_field" : [ ]}

我想写一个查询来检查 'sub_field' 是否为空。

这是我试过的:

$cursor = $collection->find( array('field1.sub_field' => array('$ne' => null))

显然它给出的结果是 Array 不为空(我试过 null 和 empty space 但徒劳无功)。

有人告诉我可以使用“$size”运算符来实现这一点。但到目前为止我运气不好。

有什么建议吗?

对于查找类型为 null 或未定义的字段,您可以使用此方法:

对于未定义的:

db.getCollection('your_collection_name').find({ yuorField: { $type: 6 } })

为空:

db.getCollection('your_collection_name').find({ yuorField: { $type: 10 } })

您可以通过多种方式解决这个问题。第一种是使用点符号和 $exists 运算符在查询对象键中使用数字数组索引来搜索至少没有 sub_field数组元素:

var cursor = db.collection.find({ "field1.sub_field.0": { "$exists": false } })

应该翻译成 PHP 为

$cursor = $collection->find( array("field1.sub_field.0" => array("$exists" => false))

另一种方法是将 $size 运算符与 [=24 一起使用=] 运算符全部包含在 $or 运算符中以查找所有没有 sub_field 的文档数组不存在或为空:

var cursor = db.collection.find({
    "$or": [
        { "field1.sub_field": { "$exists": false } },
        { "field1.sub_field": { "$size": 0 } }
    ]
});

虽然性能较慢,但您可以考虑使用另一种方法,即使用 $where 运算符:

var cursor = db.collection.find({       
    "$where": "this.field1.sub_field.length == 0"   
});

对于基准测试,请尝试填充测试集合:

db.test.insert([       
    { field1: { sub_field: [] } },
    { field1: { sub_field: [ "foo" ] } },
    { field1: { sub_field: [ "foo", "bar" ] } }
]);

> db.test.find({ "field1.sub_field.0": { "$exists": false } })
> db.test.find({
    "$or": [
        { "field1.sub_field": { "$exists": false } },
        { "field1.sub_field": { "$size": 0 } }
    ]
})
> db.test.find({ "$where": "this.field1.sub_field.length == 0" })

所有三个查询都将生成具有空 sub_field 数组的文档:

/* 0 */
{
    "_id" : ObjectId("568ccec3653d87e43482c4d0"),
    "field1" : {
        "sub_field" : []
    }
}