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


data:

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

i want write query check if 'sub_field' empty or not.

this tried:

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

obviously gives results array not null (i have tried null , empty space in futility).

i told '$size' operator can used achieve this. have had no luck far.

any suggestions ?

you approach in couple of ways. first use numeric array indexes in query object keys using dot notation , $exists operator search documents won't have @ least sub_field array element:

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

which should translate php as

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

the other way use $size operator $exists operator wrapped within $or operator find documents without sub_field either non existent or empty array:

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

another approach consider though slower performance, use $where operator:

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

for benchmark testing, try populating test collection:

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" }) 

all 3 queries yield document has empty sub_field array:

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

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -