WHITECOLOR
WHITECOLOR

Reputation: 26142

mongod db query by _id with restrictive option

Suppose I know the _id value of the document I want to update, but I want it to be updated only if say user field equal to a certain value. Is it correct way to do this

collection.update({_id: '1', user: 'correct_user'}, data) ?

Do I need to create some additional indexes for this task?

Upvotes: 0

Views: 26

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180927

Yes, it will only update if both _id and user match.

Since you're matching on exact _id which is always unique, an index on user will not really improve the query since in the end there's only at most a single value of user to compare to.

> collection.find({_id: '1', user: 'correct user'}).explain() 

{
    "cursor" : "BtreeCursor _id_",
    "isMultiKey" : false,
    "n" : 1,
    "nscannedObjects" : 1,               // Only a single object is scanned
    "nscanned" : 1,
    "nscannedObjectsAllPlans" : 1,
    "nscannedAllPlans" : 1,
...

Upvotes: 2

Related Questions