Testing for checked or missing fields in MongoDB

Is there a way to query the MongoDB database to check for fields that:

  • Have not been installed yet
  • Set to null
  • ... and as a bonus - an array that contains null as one of its values?
+4
source share
3 answers

This should cover all three of your cases:

db.FOO.find({BAR: null}); 

Literature:


You can check from the Mongo shell:

 > db.foo.drop(); true > db.foo.insert({_id:1, bar:1, matches:'NO'}); > db.foo.insert({_id:2, matches:'YES'}); > db.foo.insert({_id:3, bar:null, matches:'YES'}); > db.foo.insert({_id:4, bar:[1,2,3], matches:'NO'}); > db.foo.insert({_id:5, bar:[1,2,null], matches:'YES'}); > > db.foo.find({bar: null}); { "_id" : 2, "matches" : "YES" } { "_id" : 3, "bar" : null, "matches" : "YES" } { "_id" : 5, "bar" : [ 1, 2, null ], "matches" : "YES" } > db.foo.count({bar: null}); 3 > db.foo.count({matches: 'YES'}); 3 
+4
source
  • $ exists statement to check if a field is set or not.

  • To check if the value of the field is null , you can directly write a search request.

+3
source

Assume that for the collection name and field for the field name, the field "n" is added:

 > db.coll.insert({n:1, field:1}); // should NOT find > db.coll.insert({n:2}); // should find > db.coll.insert({n:3, field:null}); // should find > db.coll.insert({n:4, field:[1,2,3]}); // should NOT find > db.coll.insert({n:5, field:[1,2,null]}); // should find > db.coll.find({field:null}); { "_id" : ObjectId("503f089a1edeba307d051fbd"), "n" : 2 } { "_id" : ObjectId("503f089e1edeba307d051fbe"), "n" : 3, "field" : null } { "_id" : ObjectId("503f08b01edeba307d051fc0"), "n" : 5, "field" : [ 1, 2, null ] } 

Update: Leftium is really right; you only need db.coll.find({field:null}); . I am also updating my answer to reflect this.

+3
source

All Articles