MongoDB唯一索引创建 [英] MongoDB Unique Index Creation

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

问题描述

我想在MongoDB数据库中的字段上创建唯一索引.我知道我可以通过我的应用程序强制执行它,但是我也想在MongoDB数据库上强制执行它!

I would like to create a unique index on a field in my MongoDB database. I know that I could enforce it through my application, but I would like to also enforce it on the MongoDB database as well!

我正在查看以下文档:

https://docs.mongodb.org/manual/tutorial/create-an-index/

我不明白是谁在运行以下代码?

What I do not get is that who is running the following bit of code?

db.records.createIndex( { userid: 1 } )

在这种情况下,db对象是什么?我是否可以考虑使用任何初始化脚本,以便在不存在集合的情况下对其进行预填充,在不存在的情况下应用索引?有什么建议吗?

What is the db object in this case? Is there any initialisation script that I could consider so that I can pre-populate my collections if they do not exist, apply indexes if they do not exist? Any suggestions?

推荐答案

在您的应用程序中强制使用唯一的键约束是不切实际的-只是开始考虑如何做到这一点...

It is impractical to enforce a unique key constraint in your application - just start thinking through how you would do that...

您正在阅读的文章显示了mongo shell命令.安装了mongo后,打开一个外壳,键入 mongo ,您将看到mongo提示符.这是一个完整的javascript执行环境(基于V8),因此您可以在此处执行javascript中可以执行的大多数操作.

The article you are reading is showing mongo shell commands. With mongo installed, open a shell, type mongo and you will see the mongo prompt. This is a full javascript execution environment (based on V8) so you can do most anything here that you can in javascript.

命令的 db 部分引用您当前正在使用的mongo数据库.启动mongo shell时,您将自动连接到测试数据库.当您在外壳中使用记录时,您正在更改数据库.

The db part of the command refers to the mongo database your are currently using. When you start the mongo shell, you are automatically connected to the test database. When you use records in the shell, you are changing databases.

通常,我发现编写推入mongo shell的脚本更容易:在shell中重播多行命令很乏味.这是您的示例.

Usually, I find it easier to write scripts that I push to the mongo shell: replaying multi-line commands is tedious in the shell. Here is your example.

// Example collection initialization script
// USE:
//   mongo < thisFile

// connect to mongo test database
use test

// create a unique index on records
// will create collection if it does not already exist
db.records.createIndex({userId:1}, {unique:true})

// insert some test data
db.records.insert({userId:1, name:'bob'})
db.records.insert({userId:2, name:'nancy'})

// unique does not mean the field must exist in the inserted doc
db.records.insert({name:'no userId is OK'})
// but there can be only one doc without a userId
db.records.insert({name:'ohhh nooo'})

// display indexes
db.records.getIndexes()

// drop the collection so we can test the initialization script
//db.records.drop()

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

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