对于稀疏索引,请使用sparse:true。以下是创建索引的查询-
> db.demo229.ensureIndex({"ClientName":1}, {unique: true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
以下是显示索引的查询-
> db.demo229.getIndexes();
这将产生以下输出-
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.demo229" }, { "v" : 2, "unique" : true, "key" : { "ClientName" : 1 }, "name" : "ClientName_1", "ns" : "test.demo229" } ]
现在让我们删除一个索引,并将唯一索引更改为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 }
以下是显示索引的查询-
> db.demo229.getIndexes();
这将产生以下输出-
[ { "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 } ]