Mongodb避免重复输入 [英] Mongodb avoid duplicate entries

查看:119
本文介绍了Mongodb避免重复输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mongodb的新手。我可以知道如何避免重复输入。在关系表中,我们使用主键来避免它。我可以知道如何使用java在Mongodb中指定它吗?

I am newbie to mongodb. May I know how to avoid duplicate entries. In relational tables, we use primary key to avoid it. May I know how to specify it in Mongodb using java?

推荐答案

使用带的索引{唯一:true} 选项。

// everyone's username must be unique:
db.users.createIndex({email:1},{unique:true});

您还可以在多个字段中执行此操作。 请参阅文档中的此部分 有关更多详细信息和示例。

You can also do this across multiple fields. See this section in the docs for more details and examples.


MongoDB索引可以选择强加唯一键约束,这可以保证没有文档插入的索引键的值与现有文档的值匹配。

MongoDB indexes may optionally impose a unique key constraint, which guarantees that no documents are inserted whose values for the indexed keys match those of an existing document.

如果您希望 null 要从唯一键中忽略的值,那么你还必须使索引稀疏(参见此处 ),同时添加稀疏选项:

If you wish for null values to be ignored from the unique key, then you have to also make the index sparse (see here), by also adding the sparse option:

// everyone's username must be unique,
//but there can be multiple users with no email field or a null email:
db.users.createIndex({email:1},{unique:true, sparse:true});

如果要使用MongoDB Java驱动程序创建索引。尝试:

If you want to create the index using the MongoDB Java Driver. Try:

Document keys = new Document("email", 1);
collection.createIndex(keys, new IndexOptions().unique(true));

这篇关于Mongodb避免重复输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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