1

Consider the following data structure in a collection:

{
_id : ObjectId("4ec6c015482c4c8302000001"),
uid : ObjectId("4ec6c015482c4c8302003233") //reference to user's Object ID
someValue : some json object,
}

Said collection will be sharded on uid.

Between these two situations, which would be more performant for reads?

Option A)

Store References to each data structure in the users object and perform this query:

db.collection.find({_id: {$in: ids}}

Option B)

Create an index on uid and query this way:

db.collection.find({uid : ObjectId("4ec6c015482c4c8302003233")})

each result set will include 0-20 of the data structures from the collection.

Summed up: Will it be faster to find() 20 specific ID's or all objects that match an indexed ID value (the result set is also 20)

3 Answers 3

2

Option (B) is better and straightforward :

i) You do not need to store references of _ids seperately.

ii) If an index exists onuid, your query would be fast,no optimization needed.

iii) Other operations like sort, limit,findOne will work in basic syntax . With option (A),you will have to always fetch whole data and do operations on it .

Sign up to request clarification or add additional context in comments.

Comments

2

create an index on uid and the answer is simply like this.

      uid    V.S.   _id  _id  _id 
      /|\            |    |    |
  doc doc doc       doc  doc  doc

the more _ids you push into query, the more checks against _id which means extra i/o. and time for fetching document is the same.

Comments

0

If you choose Option A) and don't have an index, option B) will be more performant. Even tough if you would have all data completly in memory it is more efficient to use B) (as the application only has to compare one values, and not several).

1 Comment

_id has an automatically created index that you can't delete, unless the collection is capped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.