db.books.update({bookId:"123461"},{$set:{"bookPrice":"6.23"}})
I get the error:
update { q: { bookId: "123461" }, u: { $set: { bookPrice: "6.23" } }, multi: false, upsert: false } does not contain _id or shard key for pattern { _id: "hashed" }
But when I use below it works.
db.books.update({_id:ObjectId("54b88167498ec382221a82c2")},{$set: {"bookPrice":"6.23"}})
Why doesn't it work with the bookId
Hashed based sharding uses a hashed index of a field as the shard key to partition data across your sharded cluster. Using a hashed shard key to shard a collection results in a more even distribution of data.
Compound hashed sharding supports features like zone sharding, where the prefix (i.e. first) non-hashed field or fields support zone ranges while the hashed field supports more even distribution of the sharded data.
The reason is because you are on a sharded cluster and you are identifying the document you wish to update with an index that is neither unique nor is it the shard key however you have specified that you only want to update 1 document. (multi: false
)
Consider that when you make a query that does not include the shard key, mongodb has to scatter the query to ALL of the shards because there is no way for mongos
to figure out which shard the document might be on.
So if mongos
were to broadcast your query to all of the shards, two or more of them may find a document that matches your query and they would both update the document they found. This would violate your {multi: false}
.
Now perhaps you know that bookId
is a unique identifier, but your mongodb cluster does not. Is there any chance that you could replace bookId
with the _id
? That is, could you change the document so that instead of having a bookId
field, it has _id: "123461"
? Or if you know bookId
is unique you could just set multi: true
. Though it will not be an efficient operation since the command will have to be sent to all of the shards even though the document is only in one of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With