MongoDB 集合中的唯一文档 [英] Unique documents in a MongoDB collection

查看:51
本文介绍了MongoDB 集合中的唯一文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一个文档中存储三个 id:s 但它们只能出现一次.例如下面的文档在这个集合中只能出现一次:

I need to store three id:s in a document but they can only occur once. For example the document below can only occur once in this collection:

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

如何确保这将是 MongoDB 中的唯一文档?

How do I make sure this will be a unique document in MongoDB?

推荐答案

你可以使用 MongoDB 的唯一复合索引

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 也可能有类似的东西.请试一试.

I know I have used strings here. But something similar might also be possible with ObjectIds. Please do give it a try.

这篇关于MongoDB 集合中的唯一文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆