mongodb - Unique key in moongose db -


i have following db:

{         "_id" : objectid("556da79a77f9f7465943ff93"),         "guid" : "a12345",         "update_day" : "12:05:10 02.06.15" } {         "_id" : objectid("556dc4509a0a6a002f97e972"),         "guid" : "bbbb",         "update_day" : "15:03:10 02.06.15"         "__v" : 0 } {         "_id" : objectid("556dc470e57836242f5519eb"),         "guid" : "bbbb",         "update_day" : "15:03:10 02.06.15"         "__v" : 0 } {         "_id" : objectid("556dc47c7e882d3c2fe9e0fd"),         "guid" : "bbbb",         "update_day" : "15:03:10 02.06.15"         "__v" : 0 } 

i want set guid unique, no duplicate possible (like primary key in mysql). db this:

   {             "_id" : objectid("556da79a77f9f7465943ff93"),             "guid" : "a12345",             "update_day" : "12:05:10 02.06.15"     }     {             "_id" : objectid("556dc4509a0a6a002f97e972"),             "guid" : "bbbb",             "update_day" : "15:03:10 02.06.15"             "__v" : 0     } 

and when insert "guid":"bbbb" (with save command), fails.

first, have deal current state of mongodb collection , delete duplicated documents.

one thing sure : won't able create unique index duplicates in collection , dropdupes deprecated since version 2.7.5 can't use it. way, removed because impossible predict document deleted in process.

two possible solutions :

  1. create new collection. create unique index on new collection , run batch copy documents old collection new 1 , make sure ignore duplicated key error during process.

  2. deal in own collection manually :

    • make sure won't insert more duplicated documents in code,
    • run batch on collection delete duplicates (and make sure keep 1 if not identical),
    • then add unique index.

i declare guid in mongoose :

guid : { type : string, unique : true}


Comments