Mongo常用命令
创建集合
db.createCollection("upload_fail_file")
清空集合数据
db.getCollection('upload_fail_file').remove({})
正则匹配
db.getCollection('upload_fail_file').find({intent:/寄快递/})db.getCollection('upload_fail_file').find({intent:{$regex:"是"}})
统计条数
db.getCollection('upload_fail_file').find({}).count()
分页限数
skip(), limilt(), sort()三个放在一起执行的时候,执行的顺序是先 sort(), 然后是 skip(),最后是显示的 limit()。
db.getCollection('upload_fail_file').find({}).limit(2).skip(1)
更新某个属性
第一个false为更新,没有不更新,当为true时,没有查到会创建一条记录。
第二个true为muli,当为true更新所有,当为false只更新第一条。
更新属性
db.getCollection('upload_fail_file').update({"creator":"yipeng"},{$set:{"creator":"admin"}},false,true)
更新set内部属性
db.getCollection('upload_fail_file').update({"_id" : ObjectId("5ce548790b0018566cac1dad")},{$addToSet:{"shareUser":"admin"}},false,true)
删除记录
db.getCollection('upload_fail_file').deleteOne({"name":"吃东西"})db.getCollection('upload_fail_file').deleteOne({"_id":ObjectId("5dc91733ca0ef30007f2a120")})db.getCollection('upload_fail_file').remove({"pid":"11111"})
创建索引
db.getCollection('upload_fail_file').createIndex({"phone": 1});
创建联合索引
db.getCollection('upload_fail_file').createIndex({"online":NumberInt(-1),"modify_time":NumberInt(-1)},{"name":'idx_online_modify_time'});
显示字段的值
使用投影查询,只显示部分字段。db.集合名.find({},{需要显示的字段:1, 不需要显示的字段:0})
db.getCollection('upload_fail_file').find({},{pid:1, _id:0})db.getCollection('upload_fail_file').find({},{json_detail:0})
查找集合中有重复的openid,显示重复的openid和重复的个数
db.getCollection('upload_fail_file').aggregate([{ $group: { _id : '$pid', count: { $sum : 1 } } },{ $match: { count: { $gt : 1} } }])
查询某个时间段的信息
db.getCollection('upload_fail_file').find({}).sort({create_time:-1})db.getCollection('upload_fail_file').find({"create_time":{$gt:new Date(2019,8,8)}})db.getCollection('upload_fail_file').find({"create_time":{$lt:new Date(2019,8,8)}})db.getCollection('upload_fail_file').find({"$and":[{"create_time":{$lt:new Date(2019,8,12)}},{"create_time":{$gt:new Date(2019,8,4)}}]})
按月统计个数
db.getCollection('upload_fail_file').aggregate([{$project: {date: {$dateToString: {format: "%Y-%m-%d",date: "$create_time"}},year: {$dateToString: {format: "%Y",date: "$create_time"}},year_month: {$dateToString: {format: "%Y-%m",date: "$create_time"}},day: {$dayOfMonth: "$create_time"},responseTime: "$create_time"}},{$match: {$or: [{year: '2017'},{year: '2018'},{year: '2019'},{year: '2020'},{year: '2021'}]}},{$group: {"_id": "$year_month","sum": {$sum: 1}}},{$sort: {"_id": 1}}])
导入csv
mongoimport -d test -c phonetest --type csv --headerline --file 数据(例子).csv
导出json
mongoexport -d test -c phonetest -o c:\phoneTest.json
本文详细介绍了MongoDB中创建集合、清空数据、正则匹配、统计、分页、更新操作、删除记录、创建索引、聚合查询、CSV导入导出等实用命令,并提供了实例演示。涵盖了从基础到高级的数据库管理技巧。
701

被折叠的 条评论
为什么被折叠?



