Search code examples
phpmongodbsharding

MongoDB - Duplicate Entry Comes in Collection


Currently we are using mongodb sharding in production server and having one collection called "ordertracking" and created the shardkey using following command.

db.runCommand( { shardcollection : "OT.ordertracking", key : {OrderId : 1} } )

In this collection "_id" also we are inserting same orderid which we are updating in OrderId field. But duplicate entry was occured in this collection. But we dont know how its possible?. Because _id is a unique key how comes like this?.

Collection schema details and sample duplicate entry details for your references.

_id,OrderId,Name,City,State,Country
12,12,sara,38,12,201
12,12,sara,34,12,201
18,12,sara,32,12,201
18,12,sara,28,12,201

How will rectify this problem and please share your input.


Solution

  • Because _id is a unique key how comes like this?

    Mongo does not support unique indexes across shards. It can only enforce uniqueness for the shard key itself (or keys that include the shard key).

    Unless you shard on the _id, Mongo cannot guarantee uniqueness for it anymore (because there is no global index). So you have to take care of that by yourself in your application code.