Mongo: find items that don't have a certain field
MongodbNullExistsMongodb 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
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 });