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

2019-01-16 08:47发布

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

2条回答
Rolldiameter
2楼-- · 2019-01-16 09:23

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 and safer:

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

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

查看更多
Luminary・发光体
3楼-- · 2019-01-16 09:29

Yeah, it's possible using $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.

查看更多
登录 后发表回答