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?
3 Answers
Reset to default 4This 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
$exists operator to check if a field has been set or not.
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
版权声明:本文标题:javascript - Testing for unset or missing fields in MongoDB - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742221781a2435491.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论