关于后端:MongoDB-命令大全

3次阅读

共计 13447 个字符,预计需要花费 34 分钟才能阅读完成。

每日一句

There should be a better way to start a day than waking up every morning.
应该有更好的形式开始新一天, 而不是千篇一律的在每个上午醒来。

数据库操作

查询数据库

查看所有数据库

查看所有数据库,能够应用 show dbs 或者 show databases命令

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> show databases

查看以后的数据库

查看以后的数据库名:db 命令

> db
test
>

创立或切换数据库

语法

MongoDB 创立数据库的语法格局:use DATABASE_NAME 如果数据库不存在,则创立数据库,否则切换到指定数据库。

实例

以下实例咱们创立了数据库 test

> use test1
switched to db test1
> db
test
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

能够看到,咱们刚创立的数据库 runoob 并不在数据库的列表中,要显示它,咱们须要向 runoob 数据库插入一些数据。

> db.runoob.insert({"name":"菜鸟就是我"})
WriteResult({"nInserted" : 1})
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test1   0.000GB

MongoDB 中默认的数据库为 test,如果你没有创立新的数据库,汇合将寄存在 test 数据库中。

删除数据库

语法

MongoDB 删除数据库的语法格局:db.dropDatabase()

实例

以下实例咱们删除了数据库 test1。

# 首先,查看所有数据库
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
test1   0.000GB
# 切换到数据库 test1
> use test1
switched to db test1
# 执行删除命令
> db.dropDatabase()
{"ok" : 1}
# 查看数据库 test1 是否还存在
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
>

汇合操作

汇合,相似关系型数据库中的表。

能够显式的创立,也能够隐式的创立。

查看汇合

查看以后库中的表 / 汇合:show tables 或者 show collections 命令

> show collections
mycollection
> show tables
mycollection
>

创立汇合

显式创立汇合

语法格局db.createCollection(name)

参数阐明

  • name – 要创立的汇合名称

举例说明:创立一个名为 mycollection 的一般汇合。

> db.createCollection("mycollection")
{"ok" : 1}
> show tables
mycollection

汇合的命名标准参考:汇合的命名标准

隐式创立汇合

当向一个汇合中插入一个文档的是够,如果汇合不存在,则会主动创立汇合。

具体请看:提醒

通常咱们应用隐式创立文档即可。

删除汇合

语法格局db. 某个个体汇合名.drop()

返回值:如果胜利删除选定汇合,则 drop() 办法返回 true,否则返回 false。

示例:要删除 mycollection 汇合

> show tables
mycollection
> db.mycollection.drop()
true
> show tables
>

文档操作

文档(document)的数据结构和 JSON 根本一样。

所有存储在汇合中的数据都是 BSON 格局。对于 BSON 的介绍能够查看:数据模型

查问文档

语法格局db.collection.find(<query>, [projection])

参数阐明

Parameter Type Description
query document 可选。应用查问运算符指定抉择筛选器。若要返回汇合中的所有文档,请省略此参数或传递空文档({} )。
projection document 可选。指定要在与查问筛选器匹配的文档中返回的字段(投影)。若要返回匹配文档中的所有字段,请省略此参数

实例 1:查问所有 db.comment.find()db.comment.find({})

> db.comment.find()
{"_id" : ObjectId("61bfc69ab5617497c0621b00"), ... }
{"_id" : "1", "articleid" : "100001", ...}
{"_id" : "2", "articleid" : "100001", ...}
{"_id" : "3", "articleid" : "100001", ...}
{"_id" : "4", "articleid" : "100001", ...}
{"_id" : "5", "articleid" : "100001", ...}
> db.comment.find({})
{"_id" : ObjectId("61bfc69ab5617497c0621b00"), ... }
{"_id" : "1", "articleid" : "100001", ...}
{"_id" : "2", "articleid" : "100001", ...}
{"_id" : "3", "articleid" : "100001", ...}
{"_id" : "4", "articleid" : "100001", ...}
{"_id" : "5", "articleid" : "100001", ...}
# 按肯定条件来查问 只须要在 find()中增加参数即可
> db.comment.find({userid:'1003'})
{"_id" : "4", "articleid" : "100001",  "userid" : "1003",  ...}
{"_id" : "5", "articleid" : "100001",  "userid" : "1003",  ...}
>

提醒:每条文档会有一个叫_id 的字段,这个相当于咱们原来关系数据库中表的主键,当你在插入文档记录时没有指定该字段,MongoDB 会主动创立,其类型是 ObjectID 类型。

实例 2 :投影查问(Projection Query):要查问后果返回局部指定字段,则须要应用投影查问

# 查问后果只显示 _id、userid、nickname 
> db.comment.find({userid:"1003"},{userid:1,nickname:1})
{"_id" : "4", "userid" : "1003", "nickname" : "凯 撒"}
{"_id" : "5", "userid" : "1003", "nickname" : "凯撒"}
# 查问后果只显示、userid、nickname,不显示 _id
> db.comment.find({userid:"1003"},{userid:1,nickname:1,_id:0})
{"userid" : "1003", "nickname" : "凯 撒"}
{"userid" : "1003", "nickname" : "凯撒"}
# 查问所有数据,但只显示 _id、userid、nickname 
> db.comment.find({},{userid:1,nickname:1})
{"_id" : ObjectId("61bfc69ab5617497c0621b00"), "userid" : "1001", "nickname" : "Rose" }
{"_id" : "1", "userid" : "1002", "nickname" : "相忘于江湖"}
{"_id" : "2", "userid" : "1005", "nickname" : "伊人憔 悴"}
{"_id" : "3", "userid" : "1004", "nickname" : "杰克船 长"}
{"_id" : "4", "userid" : "1003", "nickname" : "凯 撒"}
{"_id" : "5", "userid" : "1003", "nickname" : "凯撒"}
>

插入文档

插入单个文档

应用 insert()save() 办法向汇合中插入文档。

语法格局db.collection.insert(<document or array of documents>, { writeConcern: <document>, ordered: <boolean>} )

参数阐明

Parameter Type Description
document document or array 要插入到汇合中的文档或文档数组。((json 格局)
writeConcern document Optional. A document expressing the write concern. Omit to use the default write concern.See Write Concern.Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.
ordered boolean 可选。如果为真,则按程序插入数组中的文档,如果其中一个文档呈现谬误,MongoDB 将返回而不解决数组中的其余文档。如果为假,则执行无序插入,如果其中一个文档呈现谬误,则持续解决数组中的主文档。在版本 2.6+ 中默认为 true

示例 :向 comment 的汇合(表) 中插入一条测试数据

> db.comment.insert({"articleid":"100000","content":"今天天气真好,阳光明 媚","userid":"1001","nickname":"Rose","createdatetime":new Date(),"likenum":NumberInt(10),"state":null})
WriteResult({"nInserted" : 1})
>

提醒

  • comment 汇合如果不存在,则会隐式创立
  • MongoDB 中的数数字,默认状况下是 double 类型,如果要存整型,必须应用函数 NumberInt(整型数字),否则取出来就有问题了。
  • 插入以后日期应用 new Date()
  • 插入的数据没有指定 _id , 会主动生成主键值
  • 如果某字段没值,能够赋值为 null , 或不写该字段

执行后,如下,阐明插入一条数据胜利了。

WriteResult({"nInserted" : 1})

留神

  • 文档中的键 / 值对是有序的。
  • 文档中的值不仅能够是在双引号外面的字符串,还能够是其余几种数据类型(甚至能够是整个嵌入的文档)。
  • MongoDB 辨别类型和大小写
  • MongoDB 的文档不能有反复的键。文档的键是字符串。除了多数例外情况,键能够应用任意 UTF- 8 字符。

文档键命名标准请看:文档的命名标准

批量插入文档

语法格局db.collection.insertMany([ <document 1> , <document 2>, ...], {writeConcern: <document>, ordered: <boolean>} )

参数阐明

Parameter Type Description
document document or array 要插入到汇合中的文档或文档数组。((json 格局)
writeConcern document Optional. A document expressing the write concern. Omit to use the default write concern.See Write Concern.Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.
ordered boolean 可选。一个布尔值,指定 Mongod 实例应执行有序插入还是无序插入。默认为 true。

实例:批量插入多条文章评论

> db.comment.insertMany([{"_id":"1","articleid":"100001","content":"咱们不应该把凌晨节约在手机上,衰弱很重要,一杯温水幸福你我 他。","userid":"1002","nickname":"相忘于江湖","createdatetime":new Date("2019-08- 05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"}, {"_id":"2","articleid":"100001","content":"我夏天空腹喝凉开水,冬天喝温开水","userid":"1005","nickname":"伊人憔 悴","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"}, {"_id":"3","articleid":"100001","content":"我始终喝凉开水,冬天夏天都喝。","userid":"1004","nickname":"杰克船 长","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"}, {"_id":"4","articleid":"100001","content":"专家说不能空腹吃饭,影响衰弱。","userid":"1003","nickname":"凯 撒","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"}, {"_id":"5","articleid":"100001","content":"钻研表明,刚烧开的水千万不能喝,因为烫 嘴。","userid":"1003","nickname":"凯撒","createdatetime":new Date("2019-08- 06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"} ]);
{
        "acknowledged" : true,
        "insertedIds" : [
                "1",
                "2",
                "3",
                "4",
                "5"
        ]
}

提醒

  • 插入时指定了 _id,则主键就是该值。
  • 如果某条数据插入失败,将会终止插入,但曾经插入胜利的数据不会回滚掉。

因为批量插入因为数据较多容易呈现失败,因而,能够应用 try catch 进行异样捕获解决,测试的时候能够不解决。如(理解):

> try {db.comment.insertMany([ {"_id":"1","articleid":"100001","content":"咱们不应该把凌晨节约在手机上,衰弱很重要,一杯温水幸福你我 他。","userid":"1002","nickname":"相忘于江湖","createdatetime":new Date("2019-08- 05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"}, {"_id":"2","articleid":"100001","content":"我夏天空腹喝凉开水,冬天喝温开水","userid":"1005","nickname":"伊人憔 悴","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"}, {"_id":"3","articleid":"100001","content":"我始终喝凉开水,冬天夏天都喝。","userid":"1004","nickname":"杰克船 长","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"}, {"_id":"4","articleid":"100001","content":"专家说不能空腹吃饭,影响衰弱。","userid":"1003","nickname":"凯 撒","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"}, {"_id":"5","articleid":"100001","content":"钻研表明,刚烧开的水千万不能喝,因为烫 嘴。","userid":"1003","nickname":"凯撒","createdatetime":new Date("2019-08- 06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"} ]); } catch (e) {print (e); }
BulkWriteError({
"writeErrors" : [
  {
    "index" : 0,
    "code" : 11000,
    "errmsg" : "E11000 duplicate key error collection: test1.comment index: _id_ dup key: {_id: \"1\"}",
    "op" : {
      "_id" : "1",
      "articleid" : "100001",
      "content" : "咱们不应该把凌晨节约在手机上,衰弱很重要,一杯温水幸福你我 他。",
      "userid" : "1002",
      "nickname" : "相忘于江湖",
      "createdatetime" : ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ"),
      "likenum" : NumberInt(1000),
      "state" : "1"
    }
  }
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : []})
>

更新文档

语法格局: db.collection.update(query, update, options) 或者 db.collection.update(<query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ...], hint: <document|string> // Available starting in MongoDB 4.2 } )

参数

提醒:次要关注前四个参数即可

实例

# 笼罩批改,将删除执行语句中未指定的其余的字段
> db.comment.update({_id:"1"},{likenum:NumberInt(1001)})
WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : 1})
> db.comment.find({_id:"1"})
{"_id" : "1", "likenum" : 1001}
>

# 部分批改,为了解决下面的问题,咱们须要应用修改器 $set 来实现
> db.comment.update({_id:"2"},{$set:{likenum:NumberInt(889)}})
WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : 1})
> db.comment.find({_id:"2"})
{"_id" : "2", "articleid" : "100001", ...}
>

# 批量批改 更新用户为 1003 的用户的昵称为 凯撒大帝 
## 默认只更新第一条数据
> db.comment.update({userid:"1003"},{$set:{nickname:"凯撒 2"}})
WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : 1})
> db.comment.find({userid:"1003"})
{"_id" : "4", "articleid" : "100001", "nickname" : "凯撒 2", ...}
{"_id" : "5", "articleid" : "100001", "nickname" : "凯撒", ...}
>

## 批改所有符合条件的数据,须要指定参数 {multi:true}
> db.comment.update({userid:"1003"},{$set:{nickname:"凯撒大帝"}},{multi:true})
WriteResult({"nMatched" : 2, "nUpserted" : 0, "nModified" : 2})
> db.comment.find({userid:"1003"})
{"_id" : "4", "articleid" : "100001", "nickname" : "凯撒大帝", ...}
{"_id" : "5", "articleid" : "100001", "nickname" : "凯撒大帝", ...}
>

# 列值增长的批改:如果咱们想实现对某列值在原有值的根底上进行减少或缩小,能够应用 $inc 运算符来实现。## 对 3 号数据的点赞数,每次递增 1
> db.comment.find({_id:"3"})
{"_id" : "3", "likenum" : 667, ...}
> db.comment.update({_id:"3"},{$inc:{likenum:NumberInt(1)}})
WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : 1})
> db.comment.find({_id:"3"})
{"_id" : "3", "likenum" : 668, ...}
>

删除文档

语法格局db. 汇合名称.remove(条件)

实例

# 删除_id= 1 的记录
> db.comment.remove({_id:"1"})
WriteResult({"nRemoved" : 1})
> db.comment.find({_id:"1"})
>

# 能够将数据全副删除,请慎用
> db.comment.find({})
{"_id" : ObjectId("61bfc69ab5617497c0621b00"), "articleid" : "100000", ... }
{"_id" : "2", "articleid" : "100001", ...}
{"_id" : "3", "articleid" : "100001", ...}
{"_id" : "4", "articleid" : "100001", ...}
{"_id" : "5", "articleid" : "100001", ...}
> db.comment.remove({})
WriteResult({"nRemoved" : 5})
> db.comment.find({})
>

更多查问形式

下面介绍了对于文档的一些根本查问,咱们接着学习一些对于查问的应用形式。

统计查问

统计查问应用 count() 办法。

语法格局db.collection.count(query, options)

参数阐明

Parameter Type Description
query document 查问抉择条件。
options document 可选。用于批改计数的额定选项。

实例

# 统计所有记录数
> db.comment.count()
5
>

# 按条件统计:统计 userid 为 1003 的记录条数
> db.comment.count({userid:"1003"})
2
>

分页列表查问

能够应用 limit() 办法来读取指定数量的数据,应用skip() 办法来跳过指定数量的数据。

语法格局db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

实例

# 返回指定条数的记录: 调用 limit 来返回后果(TopN),默认值 20
> db.comment.find().limit(3)
{"_id" : "1", "articleid" : "100001", ...}
{"_id" : "2", "articleid" : "100001", ...}
{"_id" : "3", "articleid" : "100001", ...}
>

# skip 办法同样承受一个数字参数作为跳过的记录条数。(前 N 个不要), 默认值是 0
> db.comment.count()
5
> db.comment.find().skip(3)
{"_id" : "4", "articleid" : "100001", ...}
{"_id" : "5", "articleid" : "100001", ...}
>


# 分页查问: 每页 2 个,第二页开始:跳过前两条数据,接着值显示 3 和 4 条数据
> db.comment.find().skip(0).limit(2)
{"_id" : "1", "articleid" : "100001", ....}
{"_id" : "2", "articleid" : "100001", ....}
> db.comment.find().skip(2).limit(2)
{"_id" : "3", "articleid" : "100001", ....}
{"_id" : "4", "articleid" : "100001", ....}
> db.comment.find().skip(4).limit(2)
{"_id" : "5", "articleid" : "100001", ....}
>

排序查问

sort() 办法对数据进行排序,sort() 办法能够通过参数指定排序的字段,并应用 1 和 -1 来指定排序的形式,其中 1 为升序排列,而 -1 是用于降序排列。

语法格局db.COLLECTION_NAME.find().sort({KEY:1})

实例

# 对 userid 和访问量进行排列
> db.comment.find().sort({userid:-1,likenum:1})
{"_id" : "2", "userid" : "1005", "likenum" : 888, ...}
{"_id" : "3", "userid" : "1004", "likenum" : 666, ...}
{"_id" : "4", "userid" : "1003", "likenum" : 2000, ...}
{"_id" : "5", "userid" : "1003", "likenum" : 3000, ...}
{"_id" : "1", "userid" : "1002", "likenum" : 1000, ...}
> db.comment.find().sort({likenum:1})
{"_id" : "3", "userid" : "1004", "likenum" : 666, ...}
{"_id" : "2", "userid" : "1005", "likenum" : 888, ...}
{"_id" : "1", "userid" : "1002", "likenum" : 1000, ...}
{"_id" : "4", "userid" : "1003", "likenum" : 2000, ...}
{"_id" : "5", "userid" : "1003", "likenum" : 3000, ...}
> db.comment.find().sort({userid:-1,likenum:-1})
{"_id" : "2", "userid" : "1005", "likenum" : 888, ...}
{"_id" : "3", "userid" : "1004", "likenum" : 666, ...}
{"_id" : "5", "userid" : "1003", "likenum" : 3000, ...}
{"_id" : "4", "userid" : "1003", "likenum" : 2000, ...}
{"_id" : "1", "userid" : "1002", "likenum" : 1000, ...}
>

提醒 skip(), limilt(), sort() 三个放在一起执行的时候,执行的程序是先 sort(), 而后是 skip(),最初是显示的 limit(),和命令编写程序无关。

正则条件查问

MongoDB 的含糊查问是通过正则表达式的形式实现的。

语法格局db. 汇合.find({字段:/ 正则表达式 /})

提醒:正则表达式是 js 的语法,间接量的写法。

实例

# 查问评论内容蕴含“开水”的所有文档
> db.comment.find({content:/ 开水 /})
{"_id" : "2", "articleid" : "100001", "content" : "我夏天空腹喝凉开水,冬天喝温开水", ...}
{"_id" : "3", "articleid" : "100001", "content" : "我始终喝凉开水,冬天夏天都喝。", ...}

# 查问评论的内容中以“专家”结尾的
> db.comment.find({content:/^ 专家 /})
{"_id" : "4", "articleid" : "100001", "content" : "专家说不能空腹吃饭,影响衰弱。", ...}
>

比拟查问

<, <=, >, >= 这个操作符也是很罕用的。

语法格局

db. 汇合名称.find({"field" : { $gt: value}}) // 大于: field > value 
db. 汇合名称.find({"field" : { $lt: value}}) // 小于: field < value 
db. 汇合名称.find({"field" : { $gte: value}}) // 大于等于: field >= value 
db. 汇合名称.find({"field" : { $lte: value}}) // 小于等于: field <= value 
db. 汇合名称.find({"field" : { $ne: value}}) // 不等于: field != value

实例

# 查问评论点赞数量大于 700 的记录
> db.comment.find({likenum:{$gt:NumberInt(700)}})
{"_id" : "1", "articleid" : "100001", ... , "likenum" : 1000, "state" : "1"}
{"_id" : "2", "articleid" : "100001", ... , "likenum" : 888, "state" : "1"}
{"_id" : "4", "articleid" : "100001", ... , "likenum" : 2000, "state" : "1"}
{"_id" : "5", "articleid" : "100001", ... , "likenum" : 3000, "state" : "1"}
>

条件连贯查问

咱们如果须要查问同时满足两个以上条件,须要应用 $and 操作符将条件进行关联。(相 当于 SQL 的 and)

如果两个以上条件之间是或者的关系,咱们应用 $or 操作符进行关联

语法格局$and:[{},{},{} ]$or:[{},{},{} ]

实例

# 查问评论汇合中 likenum 大于等于 700 并且小于 2000 的文档
> db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]})
{"_id" : "1", "articleid" : "100001", ... , "likenum" : 1000, "state" : "1"}
{"_id" : "2", "articleid" : "100001", ... , "likenum" : 888, "state" : "1"}

# 查问评论汇合中 userid 为 1003,或者点赞数小于 1000 的文档记录
> db.comment.find({$or:[ {userid:"1003"} ,{likenum:{$lt:1000} }]})
{"_id" : "2", ... , "userid" : "1005", "likenum" : 888, "state" : "1"}
{"_id" : "3", ... , "userid" : "1004", "likenum" : 666, "state" : "1"}
{"_id" : "4", ... , "userid" : "1003", "likenum" : 2000, "state" : "1"}
{"_id" : "5", ... , "userid" : "1003", "likenum" : 3000, "state" : "1"}
>

美文佳句

《牛津格言》里已经讲过一段话,让我印象很粗浅:“如果咱们仅仅想取得高兴,那很容易实现。但咱们心愿比他人更高兴,就会感到难以实现。因为咱们对于他人高兴的设想,总是超过理论情景。”

咱们经常抱怨生存有太多的不如意,总感觉本人的际遇不如他人。但其实,人最大的不如意,是不懂知足。

你好,我是 yltrcc,日常分享技术点滴,欢送关注我的公众号:ylcoder

正文完
 0