Home > English, work > How to solve a “does not contain shard key for pattern” at a Mongo WriteConcernException

How to solve a “does not contain shard key for pattern” at a Mongo WriteConcernException

A few days ago I got stuck a bit longer than normally because of a WriteConcernException in MongoDB. Inside the exception I got the message : “does not contain shard key for pattern { _id: 1.0 }”. The id was in the query, but apparently not in the right place

The query was an upsert query, which has the following syntax :

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

Since we’re using sharding Mongo needs to know on which shard the operation should be performed. Since we’re sharding on id and the id was in the query I got a bit confused. After some scavenging I found the command

db.printShardingStatus()

to display all the shard keys. At this moment I was completely sure the only shard key was on id.
Then I saw the light and tried to include the id in the query part of the update query. It worked!

Conclusion

Include the shard key in the query, not only in the update part of the update query.

Since it’s a simple solution I don’t feel the need to make a big article out of it, so I just keep it short. This blog is just a reminder for me and hopefully some search engines are directing some people here.

Sources

Mongo Reference Docs (update method)
Mongo ‘bug’ for cleaner error message
Stackoverflow question about how to view the shard keys

Categories: English, work Tags:
  1. beemboy
    4 June 2015 at 17:21

    Thanks for your article, helped me with debugging. I found this section useful: http://docs.mongodb.org/manual/reference/limits/#Single-Document-Modification-Operations-in-Sharded-Collections

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: