Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB Nested Shard Key

I have a question regarding Mongo shard keys. I have documents which are structured in the following way:

{
    "payload": {
        "id": "364e1f2c-6d4c-45fb-af19-841149286d67",
        "name": "John",
    },
    "source": "myApp",
    "version": "1.0",
    "additionalInfo": {
        "time": "2012-04-18T17:32:11+03:00"
    }
}

I'd like my shard to key to be: payload.name and additionalInfo.time. The following command fails on syntax error:

db.runCommand({ shardcollection : "collection.table", key : {additionalInfo.time: 1, payload.name: 1}})

Is it possible to create such a shard key or only top level keys are acceptable. Additionally, if I try to insert a document which does not have the shard key fields, will the insert fail?

like image 300
Noam Malter Avatar asked Apr 19 '12 12:04

Noam Malter


People also ask

What is MongoDB shard key?

The “shard key” is used to distribute the MongoDB collection's documents across all the shards. The key consists of a single field or multiple fields in every document. The sharded key is immutable and cannot be changed after sharding. A sharded collection only contains a single shard key.

Does shard key have to be unique?

Although you can have a unique compound index where the shard key is a prefix, if using unique parameter, the collection must have a unique index that is on the shard key. You cannot specify a unique constraint on a hashed index.

Where is the shard key in MongoDB collection?

For more details on the db. printShardingStatus() output, see the sharded collection section on the sh. status() page.


1 Answers

It is, you need to enclose your key fields with quotes :

db.runCommand({ shardcollection : "collection.table", key : {'additionalInfo.time': 1, 'payload.name': 1}})
like image 65
Remon van Vliet Avatar answered Sep 29 '22 07:09

Remon van Vliet