在2.x的版本可以直接这样做:
db.collection.ensureIndex({user:1},{unique:true,dropDups:true})
在3.x的版本只能导出再导入(cmd):
mongoexport -d [数据库名] -c [表名] -o [文件名字]
然后在数据库里面先删除所有数据然后新建唯一索引:
//删除数据
db.collection.remove(false)
//添加唯一索引
db.collection.ensureIndex({"key":1},{"unique":true})
然后导入(cmd):
mongoimport -d [数据库名] -c [表名] --upsert [需要导入的文件路径]
网友评论