4

Is there a way when querying a MongoDB database to test for fields that either:

  • Haven't been set yet
  • Are set to null
  • ...and as a bonus, are an array that contain null as one of their values?
Leftium
  • 16,497
  • 6
  • 64
  • 99
Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112

3 Answers3

4

This should cover all three of your cases:

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

References:


You can verify 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
Leftium
  • 16,497
  • 6
  • 64
  • 99
3
  1. $exists operator to check if a field has been set or not.

  2. To check if the value of the field is null , you can directly write a find query.

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
3

Assume coll for collection name, and field for field name (added a field "n" to differentiate):

> 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 indeed correct; you only need db.coll.find({field:null});. Updating my answer to reflect that as well.

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101