Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create an index with MongoDB?
To create an index in MongoDB, use the ensureIndex() method. Let us first create a collection using following query
> db.createCollection(&qu/ot;creatingUniqueIndexDemo");
{ "ok" : 1 }
Following is the query to create an index on the above collection:
> db.creatingUniqueIndexDemo.ensureIndex({"UserCountryName":1},{unique:true});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Following is the query to insert some documents in the above collection
>db.creatingUniqueIndexDemo.insertOne({"UserName":"John","UserAge":21,"UserCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9947bd330fd0aa0d2fe4d8")
}
>db.creatingUniqueIndexDemo.insertOne({"UserName":"Mike","UserAge":23,"UserCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9947c9330fd0aa0d2fe4d9")
}
>db.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"US"});
2019-03-26T02:57:52.670+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.creatingUniqueIndexDemo index: UserCountryName_1 dup key: { : "US" } :
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.creatingUniqueIndexDemo index: .
UserCountryName_1 dup key: { : \"US\" }",
"op" : {
"_id" : ObjectId("5c9947d8330fd0aa0d2fe4da"),
"UserName" : "Robert",
"UserAge" : 26,
"UserCountryName" : "US"
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
> db.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9947e3330fd0aa0d2fe4db")
}
Following is the query to display all documents from a collection with the help of find() method
> db.creatingUniqueIndexDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9947bd330fd0aa0d2fe4d8"),
"UserName" : "John",
"UserAge" : 21,
"UserCountryName" : "US"
}
{
"_id" : ObjectId("5c9947c9330fd0aa0d2fe4d9"),
"UserName" : "Mike",
"UserAge" : 23,
"UserCountryName" : "UK"
}
{
"_id" : ObjectId("5c9947e3330fd0aa0d2fe4db"),
"UserName" : "Robert",
"UserAge" : 26,
"UserCountryName" : "AUS"
}Advertisements