MongoDB update with matching shard key and multiple = true
MongoDB recommends that all operations update()
on a highlighted collection that specify a parameter 'multi:false'
should include a shard key in the query condition so that the query only hits a specific shard cluster. If shard key is not found and 'multi:false'
, it returns this error (see http://docs.mongodb.org/manual/core/sharded-cluster-query-router/ ):
update does not contain _id or shard key for pattern
I am switching my code to use the assembled collection. My code is using update()
c 'multi:true'
by default, and I don't want to change this default to avoid any potential error above. My question is, if I include the shard key in update()
c 'multi:true'
, would the Mongols be smart enough to redirect the request to a specific cluster using the shard key and ignore 'multi: true'
?
EDIT: Check out these codes, which confirms what @wdberkeley said.
Version 2.4:
https://github.com/mongodb/mongo/blob/v2.4/src/mongo/s/strategy_shard.cpp#L941
Version 2.6:
https://github.com/mongodb/mongo/blob/v2.6/src/mongo/s/chunk_manager_targeter.cpp#L250
source to share
Yes. If you have the shard key in your query like
> db.myShardedCollection.update({ "shardKey" : 22, "category" : "frogs" }, { "$set" : { "category" : "amphibians" } }, { "multi" : true })
then mongos can use the shard key to redirect the update only to the shard whose key range includes the value 22. Whether you update 1 document or 1000 all affected documents have shardkey = 22
, so everything will be found on a shard whose range contains 22. This also will work in case of a range request like
> db.myShardedCollection.update({ "shardKey" : { "$gte" : 22 }, "category" : "frogs" }, { "$set" : { "category" : "amphibians" } }, { "multi" : true })
except for the hashed shard keys.
source to share