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

MongodbNullExists

Mongodb Problem Overview


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

Mongodb Solutions


Solution 1 - Mongodb

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.

Solution 2 - Mongodb

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.

Solution 3 - Mongodb

just for the reference here, for those of you using mongoose (v6) and trying to use the $exists to find a field that is not defined in your mongoose schema, mongoose v6 will escape it.

see here https://mongoosejs.com/docs/migrating_to_6.html#strictquery-is-removed-and-replaced-by-strict

for example:

const userSchema = new Schema({ name: String });
const User = mongoose.model('User', userSchema);

// By default, this is equivalent to `User.find()` because Mongoose filters out `notInSchema`
await User.find({ notInSchema: 1 });

// Set `strictQuery: false` to opt in to filtering by properties that aren't in the schema
await User.find({ notInSchema: 1 }, null, { strictQuery: false });
// equivalent:
await User.find({ notInSchema: 1 }).setOptions({ strictQuery: false });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbcmcfcView Question on Stackoverflow
Solution 1 - MongodbAndrew OrsichView Answer on Stackoverflow
Solution 2 - MongodbnilskpView Answer on Stackoverflow
Solution 3 - MongodbNormalView Answer on Stackoverflow