MongoDb 部分笔记

本贴最后更新于 1917 天前,其中的信息可能已经时移俗易

查找数据

  • 部分字段不存在时查询 db.post.find({'worksAspectRatio':{$exists:false}}).count()
  • 排序查找 db.col.find({},{"title":1,_id:0}).sort({"likes":-1})
  • 更新文档
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")}})

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

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 目录下运行 mongorestore -h localhost:27017 -d test F:\文件备份\test\opt\test

删除或新增表的一个字段:

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

条件查询

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

查询相同字段的个数

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)
  • MongoDB

    MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是一个基于分布式文件存储的数据库,由 C++ 语言编写。旨在为应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型。

    90 引用 • 59 回帖 • 3 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...