mongodb Mongo:查找没有特定字段的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5719408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:04:13  来源:igfitidea点击:

Mongo: find items that don't have a certain field

mongodbnullexists

提问by bcmcfc

How to search for documents in a collection that are missing a certain field in MongoDB?

如何在集合中搜索缺少 MongoDB 中某个字段的文档?

回答by Andrew Orsich

Yeah, it's possible using $exists:

是的,可以使用$exists

db.things.find( { a : { $exists : false } } ); // return if a is missing

When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain the field.

当为真时,$exists 匹配包含该字段的文档,包括字段值为空的文档。如果为 false,则查询仅返回不包含该字段的文档。

回答by nilskp

If you don't care if the field is missing or null(or if it's never null) then you can use the slightly shorter andsafer:

如果你不关心,如果该字段缺少或null(或者,如果它从来没有null),那么你可以用略短更安全:

db.things.find( { a : null } ); // return if a is missing or null

It's safer because $existswill return trueeven if the field is null, which often is not the desired result and can lead to an NPE.

它更安全,因为即使该字段为空$exists也会返回true,这通常不是所需的结果并且可能导致 NPE。