架构- 数据库:yelp_camp, 集合:露营地, 集合中的记录数等于4
问题-集合中存在重复的记录,希望删除除第一个记录以外的所有记录。
数据库集合快照, {“ _id”:ObjectId(“ 5cc9729f48ec2b0add99866e”),“名称”:“ CampAliBaba101234”,“图像”:“ https://photosforclass.com/download/flickr-2770447094”,“ __v”:0} {“ _id”:ObjectId(“ 5cc974b46e587f0b00855b0d”),“名称”:“ CampAliBaba101234”,“图像”:“ https://photosforclass.com/download/flickr-2770447094”,“ __v”:0} {“ _id”:ObjectId(“ 5cc9facd11f218081b57f8f0”),“名称”:“ CampAliBaba101234”,“图像”:“ https://photosforclass.com/download/flickr-2770447094”,“ __v”:0} {“ _id”:ObjectId(“ 5cca658c5ecabc0a7ff79e4e”),“名称”:“ CampAliBaba101234”,“图像”:“ https://photosforclass.com/download/flickr-2770447094”,“ __v”:0} 使用以下代码尝试过,但没有成功,
下面在shell中尝试了mongo查询, db.campgrounds.ensureIndex({“ name”:1},{unique:“ true”,dropDups:“ true”})
预期- 重复的记录应该删除,并且只有一个唯一的记录应该存在。
实际- 返回以下错误, { “ ok”:0, “ errmsg”:“ E11000重复密钥错误集合:yelp_camp.campgrounds索引:image_1 dup密钥:{:\” https://photosforclass.com/download/flickr-2770447094 \“}”, “代码”:11000, “ codeName”:“ DuplicateKey” }
答案 0 :(得分:0)
只需尝试
db.getCollection('Test').find({
"name":"CampAliBaba101234"
}).forEach((data)=>{
var i = 0;
db.getCollection('Test').find( {
"name":"CampAliBaba101234"
} ).forEach((doc)=> {
if (i>0) db.getCollection('Test').remove( {
_id:data._id
} )
i++
} )
});