Getting 'query in command must target a single shard'

11,699

You need to provide shard key when you want to run commands like db.collection.remove or db.collection.deleteMany.

For example :

My data source as below:

[
    {
        "id" : "2",
        "name" : "b"
    },
    {
        "id" : "1",
        "name" : "a"
    }
]

And my shared key is "/name". Use db.coll.deleteMany({"name":"a"}) to delete specific shard.

enter image description here

Hope it helps you.

Share:
11,699
Zabi
Author by

Zabi

Updated on July 26, 2022

Comments

  • Zabi
    Zabi almost 2 years

    I have a CosmosDB setup using the Mongo API. I have a collection with a hashed shard on one of the field of the document. When I run commands like db.collection.remove or db.collection.deleteMany I get the following error.

    Command deleteMany failed: query in command must target a single shard key.: {"message":"Command deleteMany failed: query in command must target a single shard key."}

    I'm not sure how can I mention a shard key as part of the query considering I want the query to run across all the shards.

  • Zabi
    Zabi about 6 years
    Thanks for the answer Jay. As I have a shard key which is based on hash of a field, does it mean I have to query all the documents first, to get that field and then call delete for them with that field?
  • Jay Gong
    Jay Gong about 6 years
    @Zabi Yes, I think you need to query them first if you can't get them.
  • Zabi
    Zabi about 6 years
    thanks, that would make sense. It just that if I'm deleting millions of record that match a particular filter, I need to first query those millions records sharded field and then run delete. Any idea if there is a better way?
  • nicks
    nicks about 6 years
    what if I have another document {id:3,name:"a"} and I want to remove it based on the id, do I need to query both params, id (the one that identifies the document) and name (because it's a shard key), right?