mongodb集合要求某一个字段的值唯一
通过在字段建立唯一索引来实现,现在集合里存在重复的数据,创建索引报错如下:
> db.CollectedUrl.ensureIndex({uri:1},{unique:true, dropDups:true})
{
"ok" : 0,
"errmsg" : "E11000 duplicate key error collection: uxgourmet.CollectedUr
l index: uri_1 dup key: { : \"http://www.dianping.com/search/branch/3/0_13803622
/g0\" }",
"code" : 11000
}
>
dropDups选项为true时会删除集合的重复值,但现在报错了,经过查询dropDups不支持mongodb3版本了
用以下方法解决在重复数据的集合里建立唯一索引
1.首先把集合数据导出
mongoexport -d uxgourmet -c CollectedUrl -o CollectedUrl.json
2.删除集合数据
db.CollectedUrl.remove({})
3.在集合上创建唯一索引
db.CollectedUrl.ensureIndex({uri:1},{unique:true})
4.把导出数据再次导入集合中
mongoimport -d uxgourmet -c CollectedUrl --upsert D:/CollectedUrl.json
注意要加上--upsert选项
--upsert insert or update objects that already exist
通过在字段建立唯一索引来实现,现在集合里存在重复的数据,创建索引报错如下:
> db.CollectedUrl.ensureIndex({uri:1},{unique:true, dropDups:true})
{
"ok" : 0,
"errmsg" : "E11000 duplicate key error collection: uxgourmet.CollectedUr
l index: uri_1 dup key: { : \"http://www.dianping.com/search/branch/3/0_13803622
/g0\" }",
"code" : 11000
}
>
dropDups选项为true时会删除集合的重复值,但现在报错了,经过查询dropDups不支持mongodb3版本了
用以下方法解决在重复数据的集合里建立唯一索引
1.首先把集合数据导出
mongoexport -d uxgourmet -c CollectedUrl -o CollectedUrl.json
2.删除集合数据
db.CollectedUrl.remove({})
3.在集合上创建唯一索引
db.CollectedUrl.ensureIndex({uri:1},{unique:true})
4.把导出数据再次导入集合中
mongoimport -d uxgourmet -c CollectedUrl --upsert D:/CollectedUrl.json
注意要加上--upsert选项
--upsert insert or update objects that already exist