And*_*ich 166
是的,可以使用$ exists:
db.things.find( { a : { $exists : false } } ); // return if a is missing
Run Code Online (Sandbox Code Playgroud)
如果为true,则$ exists匹配包含该字段的文档,包括字段值为null的文档.如果为false,则查询仅返回不包含该字段的文档.
nil*_*skp 50
如果你不关心,如果该字段缺少或null
(或者,如果它从来没有null
),那么你可以用略短和更安全:
db.things.find( { a : null } ); // return if a is missing or null
Run Code Online (Sandbox Code Playgroud)
它更安全,因为即使该字段为空$exists
也将返回true
,这通常不是期望的结果并且可能导致NPE.