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
Change a unique index to a sparse unique index in MongoDB?
For sparse index, use sparse:true. Following is the query to create an index −
> db.demo229.ensureIndex({"ClientName":1}, {unique: true});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Following is the query to display indexes −
> db.demo229.getIndexes();
This will produce the following output −
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.demo229"
},
{
"v" : 2,
"unique" : true,
"key" : {
"ClientName" : 1
},
"name" : "ClientName_1",
"ns" : "test.demo229"
}
]
Let us now drop an index and change a unique index to a sparse unique index in MongoDB −
> db.demo229.dropIndex("ClientName_1");
{ "nIndexesWas" : 2, "ok" : 1 }
> db.demo229.ensureIndex({"ClientName":1}, {unique: true, sparse:true});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Following is the query to display indexes −
> db.demo229.getIndexes();
This will produce the following output −
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.demo229"
},
{
"v" : 2,
"unique" : true,
"key" : {
"ClientName" : 1
},
"name" : "ClientName_1",
"ns" : "test.demo229",
"sparse" : true
}
]Advertisements