Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot create unique index over {EDs._id: 1 } with shard key pattern { _id: "hashed" }

Tags:

mongodb

I'm trying to index the embedded documents where the main collection is using the hash sharding. Sample Structure:

class ED(EmbeddedDocument):
    id = StringField(primary_key=true)
    meta = {
        'indexes': [{'fields': ['EDs.id'], 'unique': True}]
    }

class D(Document):
    id = StringField(primary_key=true)
    EDs = EmbeddedDocumentListField(ED)

Now, I've added a sharding in collection D.

sh.shardCollection("db.d", { "_id" : "hashed" } )

Now since I've added indexes on ED's id, it is not allowing me to save the document.

$cmd failed: cannot create unique index over { EDs._id: 1 } with shard key pattern { _id: "hashed" }

However, when we remove this meta from ED it works. It also works when I remove sharding. So, how can we achive this indexing on embedded document ED's id?

like image 984
Kumar Nitin Avatar asked Oct 20 '25 14:10

Kumar Nitin


2 Answers

I was able to get this to work by actually including the shard key in the unique index itself.

like image 109
Dan Avatar answered Oct 22 '25 04:10

Dan


'Unique' option for createIndex, in the literature of MongoDB says: "The option is unavailable for hashed indexes" createIndex Options

So if you remove the option: {'unique': True} when you create the index, you will not get this error anymore.

like image 40
MauriRamone Avatar answered Oct 22 '25 04:10

MauriRamone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!