2
回答

在学习《MongoDB权威指南》时候,遇到索引这一节,说可以使用dropDups删除已有的重复项。
但是我编写了如下的代码却出错,不知道为什么:
> db.a.find() { "_id" : ObjectId("5507c94acdf38f5d77984d05"), "x" : 1 } { "_id" : ObjectId("5507c951cdf38f5d77984d06"), "x" : 1 } { "_id" : ObjectId("5507c964cdf38f5d77984d07"), "x" : 2 } > db.a.ensureIndex({x : 1}, {unique : 1, dropDups : 1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "errmsg" : "exception: E11000 duplicate key error index: mydb.a.$x_1 dup key: { : 1.0 }", "code" : 11000, "ok" : 0 }我查看了以下索引,发现确实没有建立:
> db.a.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.a" } ]