mongodb 去重,索引
MongoDB Community Server 下载: https://www.mongodb.com/try/download/community
GUI: The Ultimate Client, IDE and GUI for MongoDB | Studio 3T
连接
设置允许远程(局域网)连接 (windows)
在打开文件 "<你的安装目录>\MongoDB\Server\7.0\bin\mongod.cfg"
修改 bindIp
为 0.0.0.0
# network interfaces
net:
port: 27017
# bindIp: 127.0.0.1
bindIp: 0.0.0.0
重启服务!!!
若还是连不上检查防火墙端口
参考: https://blog.csdn.net/qq754772661/article/details/110876957
云数据库连接要使用 公网连接的uri地址 !!!我老是没看到搞半天, 还要添加IP白名单
常见问题:
- 如何解决连接串中账号密码包含特殊字符导致连接失败_云数据库 MongoDB 版(MongoDB)-阿里云帮助中心 (aliyun.com)
创建索引优化查询
方法: db. 集合.createIndexes() - MongoDB手册
经常查询的字段创建索引可增加查询效率
如图, 未创建前, 在 450w 的数据中查询需要约20s
创建索引
// 创建多个索引
db.getCollection("math").createIndexes([
{ "answer_id": 1 },
{ "question_id": 1 }
])
// 查看当前索引
db.getCollection("math").getIndexes();
如图效果是非常显著的, 只需要39ms
去重统计总数
采集的数据经常可能会有重复的, 所以根据field_name
去重统计总数
第一种简单, 但是数据量超过16MB会报错
db.collection.distinct("field_name").length
第二种, 使用聚合查询
db.collection.aggregate([
{
$group: {
_id: "$field_name" // 使用字段进行分组
}
},
{
$count: "totalCount" // 统计分组后的文档数量
}
])
去重后的数据导出到一个新集合中
db.collection.aggregate([
{
$group: {
_id: "$answer_id", // 根据 answer_id 进行分组
doc: { $first: "$$ROOT" } // 保留每个分组的第一条记录
}
},
{
$replaceRoot: { newRoot: "$doc" } // 将结果恢复为原始文档结构
},
{
$out: "unique_answers" // 将结果输出到新集合 unique_answers
}
])
oot: { newRoot: “$doc” } // 将结果恢复为原始文档结构
},
{
$out: “unique_answers” // 将结果输出到新集合 unique_answers
}
])