1

I am attempting to shard my database, but I am having an issue with findAndModify

I have a schema that looks like this (myCollection):

{
    "_id": "508206a9f6ded00c50f59469"
    "DatabaseId" : 91,
    "TypeId" : "5e62603c-8",
    "ItemId" : "734",
    "UserId" : "d14e3afd-d8b3-4c37-87cd-db5d89291c44"
}

I am setting my shardkey like this:

db.runCommand({enablesharding:"myDb"});
db.runCommand({
    shardcollection: "myDb.myCollection",
    key: {
        "DatabaseId" : 1,
        "TypeId" : 1,
        "ItemId" : 1
    }
});

Lets say the schema above is inserted into the database.

Now I run this query:

db.myCollection.findAndModify({
    query: {
        "DatabaseId" : 91,
        "TypeId" : "5e62603c-8",
        "ItemId" : "734",
        "UserId" : "d14e3afd-d8b3-4c37-87cd-db5d89291c44"
    },
    remove: true
});

I get this error from running the findAndModify:

findAndModifyFailed failed: {
    "errmsg" : "exception: query for sharded findAndModify must have shardkey",
    "code" : 13343,
    "ok" : 0
}

Can anyone explain to me why its saying this? or a solution for it? It seems to me that I'm doing everything that I need to.

ehftwelve
  • 2,787
  • 2
  • 20
  • 25

2 Answers2

2

Your shard key has 3 fields: databaseId, typeId and itemId.

Mongo is telling you that you can't do a findAndModify with just databaseId. I don't know why.

You need something like:

db.myCollection.findAndModify({
query: {
    "DatabaseId" : 91,
    "TypeId": "blah",
    "itemId": "foo"
    "GroupId" : "5e62603c-8",
    "Identifier" : "734",
    "UserId" : "d14e3afd-d8b3-4c37-87cd-db5d89291c44"
},
remove: true

});

ptyx
  • 4,074
  • 1
  • 19
  • 21
  • I'm sorry, GroupId and Identifier == TypeId and ItemId. I made the change in my question. – ehftwelve Oct 22 '12 at 18:12
  • 1
    According to: http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/#sharded-collections "When using findAndModify in a sharded environment, the query must contain the shard key for all operations against the shard cluster for the sharded collections." – Sebastian Nov 13 '13 at 08:19
0

To expand on ptyx's answer:

The docs on findAndModify say that it will fail for a sharded cluster if the query doesn't contain the shard key. Since you are using a compound shard key, you may need to include all three fields in the query. (See the red paragraph at the bottom).

shelman
  • 2,689
  • 15
  • 17