Link Link - 1 month ago 22
Node.js Question

How to properly use 'exist' function in mongodb like in sql?

I'm using Node.js + mongodb. I have few documents in my collection and i want to know does my collection have any document matched my condition. Of course i can simply use

myModel.find({ myField: someValue })
and check is anything comes or not. But i want to use solution like sql provides
exists
keyword? Help me, please

Edit: my bad. I forget to tell that "performance first".

Answer

MongoDB's $exists actually doesn't help you very much to find out if a certain document exists in your collection. It is used for example to give you all documents that have a specific field set.

MongoDB has no native support for an sql like exists. What you can use, however, is myModel.findOne({ myField: someValue }) and then check if it is null.

To enhance performance you can tell MongoDB to only load the object id via projection, like this:

myModel.findOne({ myField: someValue }, {_id: 1})