如何在 MongoDB 中查询“falsey”值?

Vas*_*nov 5 string boolean mongodb

我想在 Mongo 集合中查询特定字段丢失或具有在 Python 中计算为 false 的值的文档。这包括原子值null, 0, ''(空字符串), false, []。但是,包含此类值(例如['foo', '']或 just [''])的数组不是错误的并且不能匹配。我可以用 Mongo 的结构化查询来做到这一点(不求助于 JavaScript)吗?

$type 似乎没有帮助:

> db.foo.insert({bar: ['baz', '', 'qux']});
> db.foo.find({$and: [{bar: ''}, {bar: {$type: 2}}]});
{ "_id" : ObjectId("50599937da5254d6fd731816"), "bar" : [ "baz", "", "qux" ] }
Run Code Online (Sandbox Code Playgroud)

Gia*_* P. 6

这应该有效

db.test.find({$or:[{a:{$size:0}},{"a.0":{$exists:true}}]})
Run Code Online (Sandbox Code Playgroud)

只需确保该a字段内没有包含该0键的对象即可。

例如

> db.test.find()

{ "_id": ObjectId("5059ac3ab1cee080a7168fff"), "bar": [ "baz", "", "qux" ] }
{ "_id": ObjectId("5059ac48b1cee080a7169000"), "hello": 1, "bar": false, "world": 34 }
{ "_id": ObjectId("5059ac53b1cee080a7169001"), "hello": 1, "world": 42 }
{ "_id": ObjectId("5059ac60b1cee080a7169002"), "hello": 13, "bar": null, "world": 34 }
{ "_id": ObjectId("5059ac6bb1cee080a7169003"), "hello": 133, "bar": [ ], "world": 334 }
{ "_id": ObjectId("5059b36cb1cee080a7169004"), "hello": 133, "bar": [ "" ], "world": 334 }
{ "_id": ObjectId("5059b3e3b1cee080a7169005"), "hello": 133, "bar": "foo", "world": 334 }
{ "_id": ObjectId("5059b3f8b1cee080a7169006"), "hello": 1333, "bar": "", "world": 334 }
{ "_id": ObjectId("5059b424b1cee080a7169007"), "hello": 1333, "bar": { "0": "foo" }, "world": 334 }

> db.test.find({$or: [{bar: {$size: 0}}, {"bar.0": {$exists: true}}]})

{ "_id": ObjectId("5059ac3ab1cee080a7168fff"), "bar": [ "baz", "", "qux" ] }
{ "_id": ObjectId("5059ac6bb1cee080a7169003"), "hello": 133, "bar": [ ], "world": 334 }
{ "_id": ObjectId("5059b36cb1cee080a7169004"), "hello": 133, "bar": [ "" ], "world": 334 }
{ "_id": ObjectId("5059b424b1cee080a7169007"), "hello": 1333, "bar": { "0": "foo" }, "world": 334 }
Run Code Online (Sandbox Code Playgroud)