作者:curzz | 来源:互联网 | 2023-02-04 19:03
importpymongo#连接数据库clientpymongo.MongoClient(mongodb:127.0.0.1:27017)dbclient.Tendering
import pymongo
# 连接数据库
client = pymongo.MongoClient('mongodb://127.0.0.1:27017')
db = client.Tendering
collection = db.test
# 选中所有不重复的id
for item in collection.distinct('id'):# 复制第一条id相同的数据repeating = collection.find_one({'id': item})# 删除所有id相同的数据result = collection.delete_many({'id': item})# 把刚刚复制的数据加入一条到数据库collection.insert_one(repeating)
pymongo的distinct方法
db.subway.aggregate([
{
$group:{_id:{content:'$name'},count:{$sum:1},dups:{$addToSet:'$_id'}}
},
{
$match:{count:{$gt:1}}
}
]).forEach(function(it){
it.dups.shift();
db.subway.remove({_id: {$in: it.dups}});
});
db.subway.aggregate([{$group:{_id:{content:'$name'},count:{$sum:1},dups:{$addToSet:'$_id'}}},{$match:{count:{$gt:1}}}]).forEach(function(it){it.dups.shift();db.subway.remove({_id: {$in: it.dups}});});