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(我尝试过null和空格,但都是徒劳的)。

有人告诉我,"$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运算符与$exists操作符一起使用,所有操作符都封装在$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" : []
    }
}