Search code examples
mongodbnosqlsharding

MongoDB ShardingKey error: Document does not contain shard key for pattern


I'm trying to set up sharding for mongoDB. The Shard is created successfully but everytime I try to populate the collection with help of a json file, I get the following error: Document does not contain shard key for pattern Document error

Im declaring the shard using the following command:

sh.shardCollection("velo.Users",{Zipcode:1})

Sharding

mongoimport --host localhost --port 1000 --db velo --collection Users "path"

This is the json file im trying to populate my collection with:

{
"Users": [
{
    "Email": "Lars.Bouman@gmail.com",
    "Number": "156 ",
    "UserId": 1,
    "Zipcode": "2060",
    "Street": "Somméstraat",
    "City": "Antwerpen",
    "CountryCode": "BE",
    "Name": "Bouman Lars"
},
{
    "Email": "Julia.van.der.Zee@telenet.be",
    "Number": "43 ",
    "UserId": 2,
    "Zipcode": "2610",
    "Street": "Europalaan",
    "City": "Wilrijk (Antwerpen)",
    "CountryCode": "BE",
    "Name": "van der Zee Julia"
}       
]
}

I've already tried using "Users.Zipcode" but I get the same error.

Anyone knows what I'm doing wrong? Thank you in advance


Solution

  • Assuming that you want your sharded collection to contain one user per document, your json (put into a file named Users.json in this example) should be

    [
    {
        "Email": "Lars.Bouman@gmail.com",
        "Number": "156 ",
        "UserId": 1,
        "Zipcode": "2060",
        "Street": "Somméstraat",
        "City": "Antwerpen",
        "CountryCode": "BE",
        "Name": "Bouman Lars"
    },
    {
        "Email": "Julia.van.der.Zee@telenet.be",
        "Number": "43 ",
        "UserId": 2,
        "Zipcode": "2610",
        "Street": "Europalaan",
        "City": "Wilrijk (Antwerpen)",
        "CountryCode": "BE",
        "Name": "van der Zee Julia"
    }       
    ]
    

    and then assuming that your json is in a file named "Users.json" your mongoimport command would be as follows:

    mongoimport --host localhost --port 1000 --db velo --collection Users --file=Users.json --jsonArray