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

后端 未结 2 2044
情话喂你
情话喂你 2020-12-07 15:09

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

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 15:49

    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.

提交回复
热议问题