$exists checks if a field is present or not, e.g. if you want to query for all Widgets that have a color field (with any value at all, even null or empty string), then you could do: Widgets.find({color: {$exists: true}}). This doesnât seem to fit with what you are trying to do in your exampleâŚ
"CHG_1234" is a value of the ticketnumber field, not a field itself. Your query is returning nothing because there are no documents that have a "ticketnumber.CHG_1234" field.
There are documents that have a value of "CHG_1234" in the ticketnumber field. To find them, you would do something like:
Sparks.find({
"ticketnumber": "CHG_1234"
});
Youâre not dealing with subdocuments here, so donât worry about dot notation.
Thanks Pete and @Batjko, but whether it exists or not the returned object seems to be identical, so how to differentiate between one that exists vs non-existent object? Though doing a .count() on the returned object provides 1 vs 0. But this is not using the $exists keyword as Pete mentioned? So why use $exists if this can be performance just by defining the key and matching value pair?
You would use $exists if you wanted to know if some document had any value for the field youâre querying on.
A query like this:
Sparks.find({
ticketnumber: { $exists: true }
});
Will return all of the documents in your first post, because all of them have values for ticketnumber. If you had some other spark document that didnât have a value in ticketnumber (undefined), it wouldnât be returned by the $exists: true query, but it would be returned by an $exists: false query.
I hope that helps. $exists just isnât the right tool for the job here.