首页 MongoDB操作笔记
文章
取消

MongoDB操作笔记

一、查找数据

  • 部分字段不存在时查询
1
db.post.find({'worksAspectRatio':{$exists:false}}).count()
  • 排序查找
1
db.col.find({},{"title":1,_id:0}).sort({"likes":-1})
  • 更新文档
1
2
3
db.plan.update({_id:ObjectId("5bce8ffbaff8ca66f919fec1")},{$set:{'left':-1}})
db.post.update({_id:ObjectId("5ac3a35faff8ca244eaf2aec")},{$set:{"tags":["zhangsan","lisi"]}})
db.user.update({_id:ObjectId("5bf77c1faff8ca5b47d8f9a2")},{$set:{"createAt": ISODate("2018-12-17T10:50:54.738Z")}})

更新表格中没有的字段 比如:数据库中没有该字段,执行此条语句则每条没有该字段的都会加上该字段:

1
2
3
4
5
6
7
8
9
10
11
12
13
db.activity.update(
    {"beRobot" : {$exists : true}},
    {"$set" : {"beRobot" : false}},
    false,
    true
)
db.post.update({'postRate':{$exists:true}},{$set:{'postRate':'D'}})

db.post.aggregate([
    {$project:{day:{$substr:["$createAt",0,10]}}},
    {$group:{_id:"$day",number:{$sum:1}}},  
    {$sort:{_id:-1}}  
])

二、数据库备份(Linux)

  • 1、进入到/usr/bin目录下
  • 2、mongodump -h 127.0.0.1 -d test -o /opt/
  • 3、进入/opt目录
  • 4、 zip -q -r test.zip /opt/test/ 将test文件打包
  • 5、 到mongodb/bin目录下运行
    1
    
    mongorestore -h localhost:27017 -d test F:\文件备份\test\opt\test
    

三、删除或新增表的一个字段

  • 删除一个字段:
    1
    
    db.post.update({},{$unset:{'postSpecialIds':''}},false,true)
    
  • 新增一个空字符串字段:
    1
    
    db.post.update({}, {$set: {postSpecialId:""}}, {multi: 1})
    

四、条件查询

1
db.CollectionAAA.find({ "CreateTime" : { "$gte" : ISODate("2017-04-20T00:00:00Z"), "$lt" : ISODate("2017-04-21T00:00:00Z") } }).count()

五、查询相同字段的个数

1
2
3
4
5
6
7
8
9
10
11
db.profile.aggregate([
    { $group: { _id : '$userId', count: { $sum : 1 } } },
    { $match: { count: { $gt : 1} } }
])

db.user.find({
    "phone":{$regex:/^1/},
    "lastLoginAt" : { "$gte" : ISODate("2018-07-20T00:00:00Z"), "$lt" : ISODate("2018-11-09T00:00:00Z") }    	
},{
    _id:0,'phone':1, 'lastLoginAt':1
}).sort({'lastLoginAt':-1}).limit(100).skip(600)
本文由作者按照 CC BY 4.0 进行授权

SpringBoot项目集成七牛云OSS对象存储, 实现文件上传

maven项目解决部分私服依赖问题, 以github上面开源项目paascloud为例!