Table of contents
1.2.1: Select and create a database, view the database commands currently in use
1.3.1: Explicit creation of collections (understand)
1.3.2: Implicit creation of collections
1.4.2: Basic query of documents
1.5: Pagination query of documents
1.6: More queries for documents
1.6.1: Regular query with complex conditions
1: Basic common commands
1.1: Demonstration case
The data for storing article comments is stored in
MongoDB
. The data structure reference is as follows:
Database:
articledb
Op-Ed Comments
|
comment
|
||
Field Name
|
field meaning
|
Field Type
|
Remark |
_id
|
ID
|
ObjectId
或
String
|
Mongo
's primary key field
|
articleid
|
Article
ID
|
String
|
|
content
|
comments
|
String
|
|
userid
|
Reviewer
ID
|
String
|
|
nickname
|
Reviewer Nickname
|
String
|
|
createdatetime
|
datetime of the comment
|
Date
|
|
likenum
|
Likes
|
Int32
|
|
replynum
|
Replies
|
Int32
|
|
state
|
state
|
String
|
0
: invisible;
1
: visible;
|
parentid
|
Superior
ID
|
String
|
If it is 0, it means the top commenter of the article |
1.2: Database operation
1.2.1: Select and create a database, view the database commands currently in use
Syntax for selecting and creating a database:
use 数据库名称
If the database does not exist, it will be created automatically. For example, the following statement creates the
spitdb
database:
use articledb
View all database commands that you have permission to view
show dbs
或
show databases
Note
:
In
MongoDB
, the collection will only be created after the content is inserted
!
That is to say, after the collection
(
data table
) is created,
a document
(
record
) must be inserted
before the collection is actually created.
View the database commands currently in use
db
The default database in
MongoDB is
test
. If you do not select a database, the collection will be stored in
the test
database.
in addition:
The database name can be any UTF-8 string
that meets the following conditions
.
- Cannot be an empty string ( "") .
- Must not contain ' ' (space ) , . , $ , / , \ and \0 ( null character ) .
- Should be all lowercase.
- Up to 64 bytes.
Some database names are reserved, and these databases with special functions can be accessed directly.
- admin : From a permissions standpoint, this is the "root" database. If a user is added to this database, the user automatically inherits all database permissions. Some specific server-side commands can also only be run from this database, such as listing all databases or shutting down the server.
- local: This data is never replicated and can be used to store arbitrary collections limited to a single local server
- config : When Mongo is used for sharding settings, the config database is used internally to save information about sharding.
1.2.2: Delete the database
The syntax format of MongoDB
to delete a database is as follows:
db.dropDatabase()
Tip: mainly used to delete the database that has been persisted
1.3: Collection operations
A collection is similar to a table in a relational database.
Can be created explicitly or implicitly.
1.3.1: Explicit creation of collections (understand)
Basic syntax format:
db.createCollection(name)
Parameter Description:
- name: the name of the collection to create
For example: create a normal collection called
mycollection
.
db.createCollection("mycollection")
View the tables in the current library:
show tables
command
show collections
或
show tables
Collection naming convention:
- Collection name cannot be an empty string "" .
- The collection name cannot contain the \0 character (null character ) , which indicates the end of the collection name.
- Collection names cannot start with "system." , this is a reserved prefix for system collections.
- User-created collection names cannot contain reserved characters. Some drivers do support inclusion in collection names because some system-generated collections include this character. Unless you're accessing collections created by such a system, never use $ in the name .
1.3.2: Implicit creation of collections
When inserting a document into a collection, the collection is automatically created if it does not exist.
See the section Inserting
Documents
.
Tip: Usually we use implicit creation of documents.
1.3.3: Collection deletion
The syntax for collection deletion is as follows:
db.collection.drop()
或
db.集合.drop()
return value
The drop()
method returns
true
if the selected collection is dropped successfully
, otherwise it returns
false
.
For example: To delete the
mycollection
collection
db.mycollection.drop()
1.4: Document Basic CRUD
The data structure of the document (
document ) is basically the same as
JSON .
All data stored in the collection is in
BSON
format
1.4.1: Insertion of documents
(
1
) Single document insertion
Use
the insert()
or
save()
method to insert documents into the collection, the syntax is as follows:
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
parameter:
Parameter
|
Type
|
Description
|
document
|
document
or array
|
The document or array of documents to insert into the collection. (
(json
format)
|
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
|
optional. If true, the documents in the array are inserted sequentially, and if an error occurs in one of the documents,
MongoDB
will return instead
The remaining documents in the array are not processed. If false, perform an unordered insert, and continue processing if one of the documents has an error
The main documents in the array.
Defaults to true in version
2.6+
|
【Example】
To
insert a piece of test data into the
comment
collection
(
table
) :
db.comment.insert({"articleid":"100000","content":"今天天气真好,阳光明
媚","userid":"1001","nickname":"Rose","createdatetime":new Date(),"likenum":NumberInt(10),"state":null})
hint:
1
) If
the comment
collection does not exist, it will be created implicitly
2
) The number in
mongo is of
double type
by default
. If you want to store an integer, you must use the function NumberInt ( integer number ) , otherwise there will be problems when you take it out.
3
) Insert current date using
new Date()
4
) If the inserted data does not specify
_id
, the primary key value will be automatically generated
5
) If a field has no value, it can be assigned a value of
null
, or the field cannot be written.
After execution, as follows, it means that the insertion of a data is successful.
WriteResult({ "nInserted" : 1 })
Notice:
- The key / value pairs in a document are ordered.
- The value in the document can be not only the string inside the double quotes, but also several other data types (even the entire embedded document ) .
- MongoDB is type and case sensitive.
- MongoDB documents cannot have duplicate keys.
- Document keys are strings. With few exceptions, keys can use arbitrary UTF-8 characters.
Document key naming convention:
- Keys cannot contain \0 ( null character ) . This character is used to indicate the end of the key.
- . and $ have special meaning and can only be used in specific circumstances.
- Keys starting with an underscore "_" are reserved ( not strictly required ) .
( 2 ) Batch insert
grammar:
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
parameter:
Parameter
|
Type
|
Description
|
document
|
document
|
The document or array of documents to insert into the collection. (
(json
format)
|
writeConcern
|
document
|
Optional. A document expressing the
write concern
. Omit to use the default 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
|
optional. A boolean value specifying whether the
Mongod
instance should perform ordered or unordered inserts. Defaults to
true
.
|
【Example】
Batch insert multiple article comments:
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"}
]);
hint:
- If _id is specified when inserting , the primary key is the value.
- If a piece of data fails to be inserted, the insertion will be terminated, but the data that has been successfully inserted will not be rolled back.
- 因为批量插入由于数据较多容易出现失败,因此,可以使用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);
}
1.4.2:文档的基本查询
查询数据的语法格式如下:
db.collection.find(<query>, [projection])
参数:
Parameter
|
Type
|
Description
|
query
|
document
|
可选。使用查询运算符指定选择筛选器。若要返回集合中的所有文档,请省略此参数或传递空文档
(
{}
)
。
|
projection
|
document
|
可选。指定要在与查询筛选器匹配的文档中返回的字段(投影)。若要返回匹配文档中的所有字段,
请省略此参数。
|
【示例】
(
1
)查询所有
如果我们要查询
spit
集合的所有文档,我们输入以下命令
db . comment . find ()或db . comment . find ({})
这里你会发现每条文档会有一个叫
_id
的字段,这个相当于我们原来关系数据库中表的主键,当你在插入文档记录时没有指定该字段, MongoDB会自动创建,其类型是
ObjectID
类型。
如果我们在插入文档记录时指定该字段也可以,其类型可以是
ObjectID
类型,也可以是
MongoDB
支持的任意类型。
如果我想按一定条件来查询,比如我想查询
userid
为
1003
的记录,怎么办?很简单!只 要在
fifind()
中添加参数即可,参数也是
json
格式,如下:
db.comment.find({userid:'1003'})
如果你只需要返回符合条件的第一条数据,我们可以使用
fifindOne
命令来实现,语法和
fifind
一样。
如:查询用户编号是
1003
的记录,但只最多返回符合条件的第一条记录:
db.comment.findOne({userid:'1003'})
(
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" : "凯撒" }
默认
_id
会显示。
如:查询结果只显示
、
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})
1.4.3:文档的更新
更新文档的语法:
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
}
)
参数:
提示:
主要关注前四个参数即可。
【示例】
(
1
)覆盖的修改
如果我们想修改
_id
为
1
的记录,点赞量为
1001
,输入以下语句:
db.comment.update({_id:"1"},{likenum:NumberInt(1001)})
执行后,我们会发现,这条文档除了
likenum
字段其它字段都不见了,
(
2
)局部修改
为了解决这个问题,我们需要使用修改器
$set
来实现,命令如下:
我们想修改
_id
为
2
的记录,浏览量为
889
,输入以下语句:
db.comment.update({_id:"2"},{$set:{likenum:NumberInt(889)}})
这样就
OK
啦。
(
3
)批量的修改
更新所有用户为
1003
的用户的昵称为
凯撒大帝
。
//默认只修改第一条数据
db.comment.update({userid:"1003"},{$set:{nickname:"凯撒2"}})
//修改所有符合条件的数据
db.comment.update({userid:"1003"},{$set:{nickname:"凯撒大帝"}},{multi:true})
提示:如果不加后面的参数,则只更新符合条件的第一条记录
(
3
)列值增长的修改
如果我们想实现对某列值在原有值的基础上进行增加或减少,可以使用
$inc
运算符来实现。
需求:对
3
号数据的点赞数,每次递增
1
db.comment.update({_id:"3"},{$inc:{likenum:NumberInt(1)}})
1.4.4:删除文档
删除文档的语法结构:
db.集合名称.remove(条件)
以下语句可以将数据全部删除,请慎用
db.comment.remove({})
如果删除
_id=1
的记录,输入以下语句
db.comment.remove({_id:"1"})
1.5:文档的分页查询
1.5.1:统计查询
统计查询使用
count()
方法,语法如下:
db.collection.count(query, options)
参数:
提示:
可选项暂时不使用。
【示例】
(
1
)统计所有记录数:
统计
comment
集合的所有的记录数:
db.comment.count()
(
2
)按条件统计记录数:
例如:统计
userid
为
1003
的记录条数
db.comment.count({userid:"1003"})
提示:
默认情况下
count()
方法返回符合条件的全部记录条数。
1.5.2:分页列表查询
可以使用
limit()
方法来读取指定数量的数据,使用
skip()
方法来跳过指定数量的数据。
基本语法如下所示:
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
如果你想返回指定条数的记录,可以在
fifind
方法后调用
limit
来返回结果
(TopN)
,默认值
20
,例如:
db.comment.find().limit(3)
skip
方法同样接受一个数字参数作为跳过的记录条数。(前
N
个不要),默认值是
0
db.comment.find().skip(3)
分页查询:需求:每页2个,第二页开始:跳过前两条数据,接着值显示3和4条数据
db.comment.find().skip(0).limit(2)
//第二页
db.comment.find().skip(2).limit(2)
//第三页
db.comment.find().skip(4).limit(2)
1.5.3:排序查询
sort()
方法对数据进行排序,
sort()
方法可以通过参数指定排序的字段,并使用
1
和
-1
来指定排序的方式,其中
1
为升序排列,而
-1
是用于降序排列。
语法如下所示:
db.COLLECTION_NAME.find().sort({KEY:1})
或
db.集合名称.find().sort(排序方式)
例如:
对
userid
降序排列,并对访问量进行升序排列
db.comment.find().sort({userid:-1,likenum:1})
提示:
skip(), limilt(), sort()三个放在一起执行的时候,执行的顺序是先 sort(), 然后是 skip(),最后是显示的 limit(),和命令编写顺序无关。
1.6:文档的更多查询
1.6.1:正则的复杂条件查询
MongoDB
的模糊查询是通过
正则表达式
的方式实现的。格式为:
db.collection.find({field:/正则表达式/})
或
db.集合.find({字段:/正则表达式/})
提示:正则表达式是
js
的语法,直接量的写法。
例如,我要查询评论内容包含
“
开水
”
的所有文档,代码如下:
db.comment.find({content:/开水/})
如果要查询评论的内容中以
“
专家
”
开头的,代码如下:
db.comment.find({content:/^专家/})
1.6.2:比较查询
<, <=, >, >=
这个操作符也是很常用的,格式如下
:
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)}})
1.6.3:包含查询
包含使用
$in
操作符。 示例:查询评论的集合中
userid
字段包含
1003
或
1004
的文档
db.comment.find({userid:{$in:["1003","1004"]}})
不包含使用$nin操作符。 示例:查询评论集合中userid字段不包含1003和1004的文档
db.comment.find({userid:{$nin:["1003","1004"]}})
1.6.4:条件连接查询
我们如果需要查询同时满足两个以上条件,需要使用
$and
操作符将条件进行关联。(相 当于
SQL
的
and
)
格式为:
$and:[ { },{ },{ } ]
示例:查询评论集合中
likenum
大于等于
700
并且小于
2000
的文档:
db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]})
如果两个以上条件之间是或者的关系,我们使用 操作符进行关联,与前面
and
的使用方式相同 格式为:
$or:[ { },{ },{ } ]
示例:查询评论集合中
userid
为
1003
,或者点赞数小于
1000
的文档记录
db.comment.find({$or:[ {userid:"1003"} ,{likenum:{$lt:1000} }]})
1.7:常用命令查询
选择切换数据库:use articledb
插入数据:db.comment.insert({bson数据})
查询所有数据:db.comment.find();
条件查询数据:db.comment.find({条件})
查询符合条件的第一条记录:db.comment.findOne({条件})
查询符合条件的前几条记录:db.comment.find({条件}).limit(条数)
查询符合条件的跳过的记录:db.comment.find({条件}).skip(条数)
修改数据:db.comment.update({条件},{修改后的数据}) 或db.comment.update({条件},{$set:{要修改部分的字段:数据})
修改数据并自增某字段值:db.comment.update({条件},{$inc:{自增的字段:步进值}})
删除数据:db.comment.remove({条件})
统计查询:db.comment.count({条件})
模糊查询:db.comment.find({字段名:/正则表达式/})
条件比较运算:db.comment.find({字段名:{$gt:值}})
包含查询:db.comment.find({字段名:{$in:[值1,值2]}})或db.comment.find({字段名:{$nin:[值1,值2]}})
条件连接查询:db.comment.find({$and:[{条件1},{条件2}]})或db.comment.find({$or:[{条件1},{条件2}]})