Best way to query for document existence

46 views
Skip to first unread message

Peter

unread,
Jun 7, 2012, 9:44:09 AM6/7/12
to mongodb-user
Hi there,

we currently do these kind of queries by checking whether:
count(query) > 0

however, this might not be the best solution for huge collections, as
count does not stop traversing the collection after the first match,
as would be feasible for this use case.

So I was wondering whether checking upon a find(query).limit(1) might
be a better solution?

Also, how about a seperate exists(query) command?

Max Schireson

unread,
Jun 7, 2012, 9:52:13 AM6/7/12
to mongod...@googlegroups.com

That should be better for exactly the reason you state. Be sure to drop any sorts which are part of your query.

Submit the request for exists on JIRA. Seems useful to me. In some cases it could be slightly faster by not returning results (eg if the document that matched first was big - which is the one downside I see to your approach but it strikes me as overall better than a count).

-- Max

--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

Peter

unread,
Jun 7, 2012, 11:47:22 AM6/7/12
to mongodb-user
Reply all
Reply to author
Forward
0 new messages