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
   }
]

Updated on: 30-Mar-2020

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements