admin管理员组

文章数量:1331656

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?

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?
Share Improve this question edited Aug 30, 2012 at 6:47 Leftium 18k6 gold badges71 silver badges109 bronze badges asked Aug 30, 2012 at 6:05 Alexander TrauzziAlexander Trauzzi 7,41516 gold badges73 silver badges124 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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
  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.

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.

本文标签: javascriptTesting for unset or missing fields in MongoDBStack Overflow