1. Core concepts
1.1 Library (Database)
MongoDB中的库就类似于传统关系型数据库中库的概念,用来通过不同库隔离不同应用数据
Multiple databases can be created in Mongodb , and each database has its own 集合(Collection)
rights and permissions. Different databases are also placed in different files. The default database is test , and the database is stored in the data directory specified at startup.
1.2 Collection
表
A collection is a MongoDB document group, similar to the concept in RDBMS (relational database)
Collections exist in the database, and multiple collections can be created in one library. Each collection has no fixed structure, which means that different formats and types of data can be inserted into the collection, but usually the data we insert into the collection will have certain relevance
1.3 Documentation
A record in a document collection is a set of key-value pairs (ie BSON)(相当于数据库表中的一条条记录)
. MongoDB documents do not need to set the same fields, and the same fields do not need to have the same data type, which is different from relational databases. There is a big difference, and it is also a very prominent feature of MongoDB.
A simple document example
{
"name":"张三", "age":"23"}
1.4 Relationship summary
RDBMS | MongoDB |
---|---|
database | database |
surface
|
gather |
OK | document |
List | field |
2. Basic use
2.1 library
certified
The client connects to the server and enters test
the database by default, but if we enable authentication in the configuration file, (auth = true)
then we need to switch to the admin database for authentication first, refer to ,
view all libraries
show databases;
show dbs
演示
注意
admin
: From the perspective of permissions, this is the "root" database. If a user is added to this database, the user automatically inherits the permissions of all databases. Some specific server-side commands can only be run from this database, such as listing all databases or shut 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
Create a database & view the currently used database
use 库名
db;
Note: use means to create and use , 当库中没有数据时默认不显示这个库
,
delete database
默认删除当前选中的库
db.dropDatabase()
2.2 Collection
View all collections in the library
show collections;
show tables
create collection
db.createCollection('集合名称',[options])
options可以是如下参数
field | type | describe |
---|---|---|
capped | Boolean | (可选) If true, create 固定集合 . A fixed collection is a collection with a fixed size that automatically overwrites the oldest documents when the maximum value is reached . When the value is true, the size parameter must be specified. |
size | value | (可选) Specify a maximum value, in bytes, for capped collections. If capped is true, this field also needs to be specified. |
max | value | (可选) Specifies the maximum number of documents contained in a capped collection |
Note: Inserting a document into a collection will also automatically create the collection if it does not exist
delete collection
db.集合名字.drop()
2.3 Documentation
2.3.1 Insertion
注意:在MongoDB中每个文档都会有一个_id作为唯一标识,_id默认会自动生成,如果手动指定将使用手动指定的值作为_id的值
single document
> db.集合名称.insert({
...})
multiple documents
> db.集合名称.insertMany(
[文档1, 文档二, ...],
{
writeConcern: 1, //写入策略,默认为1,及要求确认写操作,0是不要求
ordered: true //指定是否按顺序写入,默认为true
}
)
> db.集合名称.insert(
[文档1, 文档2,...]
)
2.3.2 Query all
> db.集合名称.find()
2.3.3 Delete document (simple delete)
> db.集合名称.remove(
<query>,
{
justOne: <boolean>
writeConcern: <document>
}
)
参数说明:
- query :
可选
Criteria for deleted documents (also in BSON format) - justOne :
可选
, if set to true or 1, only one document will be deleted, if this parameter is not set, or the default value is false, all documents matching the condition will be deleted - writeConcern:
可选
, the level of the exception thrown
example
> db.集合名.remove({}) #删除所有
> db.集合名.remove({_id:12}) #根据_id删除
...
2.3.4 update
> db.集合名称.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
参数说明
- query : query condition of update, similar to where condition of sql-update query
- update : update object and some update operators (eg , ,, inc…),etc., can also be understood as the set behind the sql-update query
- upsert :
可选
, this parameter means that if there is no update record, it is enough to insert. true means insert, the default is false, no insert - multi :
可选
, mongodb defaults to false, and only updates the first record found. If this parameter is true, all multiple records found will be updated according to the conditions (generally, the display is set to true) . - writeConcern :
可选
, the level at which the exception was thrown
示例
- db.集合名.update({
"name":"张三"}, {name:"李四", age:13})
将集合中name=张三的所有记录更新为 {name:"李四", age:13}, 相当于先删除在更新,不保留原始数据
#加上$set保留原始数据
-db.集合名称.update({
"name":"xiaohei"}, {$set:{name:"xiaobai"}})
将集合中第一条name=xiahei的文档,保留文档中的其他数据,只将name更新为xiaobai
-db.集合名称.update({
"name":"小黑"}, {$set:{name:"xiaoming"}}, {multi:true})
保留原始文档进行更新,更新所有符合条件的数据
-db.集合名称.update({name:"小黑"}, {$set:{name:"小明"}}, {multi:true, upsert:true})
保留原始数据进行更新,更新符合条件的所有数据,没有条件符合时插入数据
3. Document query details
MongoDB queries documents using the find() method, which displays all documents in an unstructured manner
语法
> db.集合名称.find(query, projection)
query
: Optional, use query operators to specify query conditionsprojection
: Optional, use the projection operator to return the specified key (equivalent to the sql-select statement only querying the specified column) , and return all key values in the document when querying, just omit this parameter.
If you need to read data in an easy-to-read way, you can use the pretty() method, the syntax is as follows
> db.集合名称.find().pretty()
Note: The pretty() method displays all documents in a formatted manner
3.1 Range query
对比语法
3.2 AND query
- The find() method of MongoDB can pass in multiple keys (keys), each key (key) is separated by a comma, which is the AND condition of regular SQL.
- AND query, if a field appears multiple times, then only the last time of the field is the main
> db.集合名称.find({key1:value1, key2:value2}).pretty()
类似于where语句 where key1 = value1 and key2 = value2
3.3 OR query
The MongoDB OR conditional statement uses the keyword $or, and the syntax is as follows
> db.集合名称.find(
{
$or:[
{key1:value1}, {key2:value2}
]
}
).pretty()
3.4 Combined use of AND and OR
The following example demonstrates the combined use of AND and OR, similar to a regular SQL statement: 'where likes>50 AND (by = 'A' OR title = 'B')'
> db.col.find({
"likes": {$gt:50}, $or: [{
"by": "A"},{
"title": "B"}]}).pretty()
3.5 Array query
-- 准确查询,即数组中的值必须完全等于查询条件才匹配
> db.集合名称.find({likes:[A, B]})
-- 包含查询,即只要数组包含某个值即匹配,跟上面的不同就是不加[]
> db.集合名称.find({likes:A})
-- $size 按照数组长度查询
> db.集合名称.find({likes:{$size:3}})
3.6 Fuzzy query
MongoDB的模糊查询依靠的是正则表达式
> db.集合名称.find({name:/xxx/(一段正则表达式)})
3.7 Sorting
-- 按照A升序排序,A相同按照B升序排序
> db.集合名称.find().sort({A:1, B:1})
-- 1升序,-1降序
3.8 Pagination
-- 跳过前start条数据,展示rows条数据
> db.集合名称.find().skip(start).limit(rows)
3.9 Count
> db.集合名称.count() -- 查询总记录数
> db.集合名称.find().count -- 查询符合条件的总记录数
3.10 Deduplication
> db.集合名称.distinct('字段')
3.11 Return to the specified field (projection)
> db.集合名称.find({条件}, {name:1, age:1})
-- 1表示保留字段 0表示舍弃字段 注意:1和0不能同时使用
4. $type operator
$type按照数据类型进行查询
Note: By default, numbers in mongoDB are of type Double
type table
example
If you want to get the data whose title is String in collection A, you can use the following command:
db.A.find({
"title" : {$type : 2}})
或
db.A.find({
"title" : {$type : 'string'}})