Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query MongoDB to test if an item exists?

Tags:

find

mongodb

Does MongoDB offer a find or query method to test if an item exists based on any field value? We just want check existence, not return the full contents of the item.

like image 492
user646584 Avatar asked Dec 05 '11 18:12

user646584


People also ask

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do you check if an array contains a value in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do I find a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


1 Answers

Since you don't need the count, you should make sure the query will return after it found the first match. Since count performance is not ideal, that is rather important. The following query should accomplish that:

db.Collection.find({ /* criteria */}).limit(1).size(); 

Note that find().count() by default does not honor the limit clause and might hence return unexpected results (and will try to find all matches). size() or count(true) will honor the limit flag.

If you want to go to extremes, you should make sure that your query uses covered indexes. Covered indexes only access the index, but they require that the field you query on is indexed. In general, that should do it because a count() obviously does not return any fields. Still, covered indexes sometimes need rather verbose cursors:

db.values.find({"value" : 3553}, {"_id": 0, "value" : 1}).limit(1).explain();  {   // ...   "cursor" : "BtreeCursor value_1",   "indexOnly" : true,  // covered! } 

Unfortunately, count() does not offer explain(), so whether it's worth it or not is hard to say. As usual, measurement is a better companion than theory, but theory can at least save you from the bigger problems.

like image 86
mnemosyn Avatar answered Sep 20 '22 09:09

mnemosyn