mongodb备忘录

MongodbVersion:4.0.28
mongodb官网下载地址
compass下载地址

下载完成后zip解压

  • 在项目根目录创建文件夹 :
    • data/db
    • conf/mongod.conf
storage:
  #The directory where the mongod instance stores its data.Default Value is "\data\db" on Windows.
  dbPath: D:\env\mongodb4.0.28\data\db
  • 启动
    • mongod --config …/conf/mongod.conf

基本使用命令

  • 库相关
# 如果没有testdb这个库就创建,有的话就选择
use testdb

# 查看有哪些库( use db 创建一个空库,这个库在内存中即使创建了也看不见,除非给这个库添加一个集合)
show dbs

# 显示当前的数据库
db

# 删库
db.dropDatabase()
  • 集合相关
# 查看集合
show collections

# 删除集合 comment为集合名称
db.comment.drop()
  • 文档相关
 # 没有comment集合会隐式创建,再在该集合下插入数据
 # 插入单条json
 db.comment.insert({
        "id": 208,
        "userId": 616,
        "content": "把具体",
        "createTime": "2022-02-22 13:17:00",
        "articleId": 166,
        "replyId": 0,
        "replyNo": 0,
        "head": "http://andiver-master.oss-cn-beijing.aliyuncs.com/2021/01/07/1609983433352.jpg",
        "nickname": "91"
      })
      
# 插入多条json (可以写try catch)
 db.comment.insertMany([ {json1}, {json2} ] )

# 查询文档数据
 db.comment.find()      
 
# 查询文档数据带参数
 db.comment.find({id:208})    

# 查询只需要返回第一条数据   
 db.comment.findOne({id:208})    
 
# 筛选返回字段,第一个json为查询条件,第二个json为返回字段
# 查询ID208的评论,返回字段只需要createTime,nickname
db.comment.find({id: 208}, {createTime:1, nickname:1 })

# 将ID208的评论的content修改为'基操勿6'
db.comment.updateOne({id: 208},{$set:{content:'基操勿6'}})

# 将ID为208的评论的replyNo自增10 (评论数,点赞数等自增业务), 自减就自增一个负数
db.comment.updateOne( {id:208}, {$inc:{replyNo:10}} )

# 删除ID206的评论数据
db.comment.deleteOne({id:206})
  • 查询相关(simple)
# 统计articleId为166的评论数据条数
db.comment.countDocuments({articleId:166})	

# 获取前两条数据
db.comment.find().limit(2)	

# 跳过前两条数据
db.comment.find().skip(2)	

# 分页
db.comment.find().skip(10).limit(10)

#根据id降序 (1:是升序,-1:是降序)
db.comment.find().sort({id:-1})
  • 查询相关(normal)
# 正则查询
# 语法:db.comment.find({字段:/正则表达式/})
# 查询content字段包含 基操 的评论数据
db.comment.find({content:/基操/})

# 查询content字段以 引战开头 的评论数据
db.comment.find({content:/^引战/})

# 比较查询
# $gt 大于, $lt 小于, $gte 大于等于, $lte 小于等于, $ne不等于
# 查询articleId大于166的数据
db.comment.find({articleId:{$gt:166}})

# in 和mysql的in差不多
# mysql: select * from comment where id in(207, 209)
db.comment.find({id:{$in:[207, 209]}})

# 条件查询 $and  $or
# and 语法 { $and:[{条件一}, {条件二}, {条件三}] }
# 查询 userId为616 and articleId 大于等于 167 的评论数据
db.comment.find({ $and:[{userId:616}, {articleId:{$gte:167}}] })

  • 索引相关
# 查询索引
 db.comment.getIndexes()

# 创建索引
# 为userId创建升序索引, -1降序
db.comment.createIndex({userId:1})

#复合索引 为userId创建升序索引, articleId创建降序索引
db.comment.createIndex({userId:1, articleId:-1})

# 删除索引
db.comment.dropIndex({userId:1})

# 删除所有索引
db.comment.dropIndexes()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值