MongoDB在多个字段上的唯一索引
我正在使用MongoDb数据库,我需要使多个字段唯一.我需要MongoDb检查多个字段的 combination 是否唯一.让我们展示一个我需要的例子:
I'm using a MongoDb database and I need to make multiple fields unique. What I need is for MongoDb to check if the combination of the multiple fields are unique. Let's show an example of what I need:
如果在添加索引后按以下顺序在数据库中添加以下内容: {"name":"paul","age":"21"}
{"name":"goerge","age":"21"}
{名称":保罗",年龄":"44"}
{"name":"paul","age":"21"}
If I add the following in this order in the database after adding the indexes: {"name":"paul", "age":"21"}
{"name":"goerge", "age":"21"}
{"name":"paul", "age":"44"}
{"name":"paul", "age":"21"}
在下面的示例中,将不被接受的 only 是最后一个.
In the following example, the only one who would not be accepted would be the last one.
我尝试了以下唯一的复合索引,但它不起作用.在前面的示例中,它将仅保留第一个字段,因为它检查每个字段是否唯一:
I've tried the following unique compound index and it doesn't work. In the preceding example, it would only keep the first one as it checks if every field is unique:
db.test.createIndex({"name":1,"age":1},{unique:true})
我也尝试过,同样的问题:
I also tried, same problem:
db.test.createIndex({"name":1},{unique:true})
db.test.createIndex({"age":1},{unique:true})
我搜索了几个小时,却找不到任何可以使我做到这一点的东西.
I searched for hours and couldn't find anything that would enable me to do that.
有人知道吗?
您无法创建唯一的索引,因为您已经有了&年龄不是唯一的!检查保罗21岁如果您修复该值.创建索引的最佳方法就是这种方法db.test.createIndex({"name":1,"age":1},{unique:true})
You aren't able to create that index unique because you 've got the name & age not unique! Check Paul 21 years olds If you fix that value. The best way to create the index is this one db.test.createIndex({"name":1, "age":1}, {unique:true})