Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What's the fastest way to check for the existence of a mongodb doc?

What's the fastest way to check for the existence of a mongodb doc?

Problem

What's the Fastest way to check for the existence of a mongodb doc?

Should I just use find and if it returns nothing?

EDIT:

collection.findOne {#attribute}, (err, doc) ->

    if err then console.log err

    if interaction
        #exists
    else
        #does not
Problem courtesy of: boom

Solution

If you are just testing for a single document, use findOne (or the equivalent in your driver); most drivers implement this in the most efficient possible way (by setting a negative limit of 1 on the request, which asks mongo to return immediately after finding one document, even if more might match, and not to create a cursor that won't ever be used by the client).

If you have an index that can serve your query, you can use field selection to select (a subset of) the fields in the index; this will make use of Mongo's "covered index" functionality to avoid a lookup to the underlying collection data. Be sure to set {_id: 0} in your field selector unless _id is in your index.

Solution courtesy of: dcrosta

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

What's the fastest way to check for the existence of a mongodb doc?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×