a way to check if a document exists in a collection?

2,814 views
Skip to first unread message

oferfort

unread,
Oct 24, 2010, 8:16:42 PM10/24/10
to mongodb-user
Hey,
I'm trying to figure out the best way (regarding performance) to check
if a document with a certain _id exists in a collection.
I know i can just query for it, but that doesn't seem too efficient.
I guess my question is this:
if i do db.collection.find({_id: 12345}, {_id: 1}), will it not go to
the disk at all, since the _id is in memory already, and just return
12345 if the document exists, or null if it doesn't?

thanks

Scott Hernandez

unread,
Oct 24, 2010, 8:19:47 PM10/24/10
to mongod...@googlegroups.com
That is probably a good query but I don't think the server will return
data from the index for the document. But when it does that will be
the most efficient. You can follow
http://jira.mongodb.org/browse/SERVER-192

> --
> 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.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

oferfort

unread,
Oct 24, 2010, 8:37:40 PM10/24/10
to mongodb-user
thanks,
let me continue with another question.

I'm trying to move some of my old data from my old MySQL to the mongo
server.
Most of the data was already moved, but some of it is not.
I'm trying to figure out what would be "cheaper":

1. Doing an insert to a document with the requested _id, and failing
internally if the _id already exist. (if it exists i don't want to
update it)
2. To query for the object, and to do an insert only if it doesn't
exist.

thanks


On Oct 25, 2:19 am, Scott Hernandez <scotthernan...@gmail.com> wrote:
> That is probably a good query but I don't think the server will return
> data from the index for the document. But when it does that will be
> the most efficient. You can followhttp://jira.mongodb.org/browse/SERVER-192

Eliot Horowitz

unread,
Oct 24, 2010, 10:22:10 PM10/24/10
to mongod...@googlegroups.com
Depends on the % that's already there. If its mostly there already,
querying will be faster. If its mostly not there, then just inserting
will be faster.

Ofer Fort

unread,
Oct 25, 2010, 2:43:44 AM10/25/10
to mongod...@googlegroups.com
most of it is already there, so i guess i'll go with the query
thanks
Reply all
Reply to author
Forward
0 new messages