0

Let's say I have the following data in a MongoDB collection:

[{ "food": "cheese", "group": "dairy" }, { "food": "chicken", "group": "meat" }]

If I wanted to find out whether any documents match a particular condition, e.g. belongs to the "dairy" food group, I could write the following query:

db.collection.count({ group: 'dairy' })

and check if the result is bigger than 0.

The above operation might be expensive if the query in question is complex or not well indexed.

So I was wondering whether there was a query that would start looking for documents that matched a query, and stop execution and return false once one document did?

In the above example, it should see the first document { "food": "cheese", "group": "dairy" } and return false immediately.

rouan
  • 5,339
  • 6
  • 22
  • 36
  • Probably easiest to use `findOne` for that. If the result is `null`, the count is 0, otherwise there's at least one. – JohnnyHK Jun 21 '17 at 03:34
  • Actually the best performance is `.find(query).limit(1)` which for arcane reasons actually runs faster than `.findOne()`. Noted in the [duplicate question anyway.](https://stackoverflow.com/questions/25163658/mongodb-return-true-if-document-exists) – Neil Lunn Jun 21 '17 at 04:03

0 Answers0