Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for unset or missing fields in MongoDB

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?
like image 973
Alexander Trauzzi Avatar asked Dec 26 '22 18:12

Alexander Trauzzi


2 Answers

This should cover all three of your cases:

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

References:

  • Querying and nulls
  • Advanced Queries: Value in an Array

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
like image 172
Leftium Avatar answered Dec 29 '22 10:12

Leftium


  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.

like image 42
DhruvPathak Avatar answered Dec 29 '22 08:12

DhruvPathak