nosql - Unique documents in a MongoDB collection -


i need store 3 id:s in document can occur once. example document below can occur once in collection:

{   "user": objectid("j8uwh902w5489"),   "comment": objectid("09890583457jkjsf4"),   "whatever": objectid("j8uwh902w5489") } 

how make sure unique document in mongodb?

well can use mongodb's unique compound index

db.users.createindex( { user: 1, comment: 1, whatever: 1 }, { unique: true } ) 

a few cases:

> db.users.insert({user: "a", comment: "b", whatever: "c"}) writeresult({ "ninserted" : 1 }) > db.users.insert({user: "a", comment: "c", whatever: "b"}) writeresult({ "ninserted" : 1 }) > db.users.insert({user: "a", comment: "b", whatever: "c"}) > writeresult({      "ninserted" : 0,     "writeerror" : {             "code" : 11000,             "errmsg" : "insertdocument :: caused :: 11000 e11000 duplicate key error index: test.users.$user_1_comment_1_whatev er_1  dup key: { : \"a\", : \"b\", : \"c\" }"     } }) 

i know have used strings here. similar might possible objectids. please give try.


Comments