我需要在文档中存储三个id:s但它们只能出现一次。例如,下面的文档只能在此集合中出现一次:
{
"user": ObjectId("j8uwh902w5489"),
"comment": ObjectId("09890583457jkjsf4"),
"whatever": ObjectId("j8uwh902w5489")
}
如何确保这是MongoDB中的唯一文档?
答案 0 :(得分:1)
db.users.createIndex( { user: 1, comment: 1, whatever: 1 }, { unique: true } )
一些案例:
> 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 by :: 11000 E11000 duplicate key error index: test.users.$user_1_comment_1_whatev
er_1 dup key: { : \"A\", : \"B\", : \"C\" }"
}
})
我知道我在这里使用了字符串。但是ObjectIds也可能有类似的东西。请试一试。