Reputation: 15385
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!
I'm looking at the following documentation:
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 } )
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?
Upvotes: 0
Views: 465
Reputation: 3228
It is impractical to enforce a unique key constraint in your application - just start thinking through how you would do that...
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.
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.
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()
Upvotes: 2