一,数据库操作
1,Create Database
语法:
use <database name>
- 无则创建,有则使用。
示例:
> use mydb
switched to db mydb
确认数据库是否存在:
> db
mydb
这表明正在使用mydb数据库。
2, Drop Database
语法:db.dropDatabase()
- 要删除数据库,请首先确保正在使用该数据库。
示例:
> use mydb
switched to db mydb
>
> db.dropDatabase()
{ "ok" : 1 }
3,Display List of Databases
语法:show dbs
或show databases;
- show databases;用到了mongodb中为数不多的’;‘这个符号。
示例:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
>
> show databases;
admin 0.000GB
config 0.000GB
local 0.000GB
>
- 新创建的数据库mydb未显示在列表中。这是因为数据库需要至少一个集合来显示在列表中。
4, Display the Version of MongoDB
语法:db.version()
示例:
> db.version()
4.2.8
5,Display a List of Commands
语法:db.help()
示例:
> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
db.aggregate([pipeline], { options}) - performs a collectionless aggregation on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - will only function with MongoDB 4.0 and below
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost) - will only function with MongoDB 4.0 and below
db.createCollection(name, { size: ..., capped: ..., max: ...})
db.createUser(userDocument)
db.createView(name, viewOn, [{ $operator: { ...}}, ...], { viewOptions})
db.currentOp() displays currently executing operations in the db
db.dropDatabase(writeConcern)
db.dropUser(username)
db.eval() - deprecated
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections db.getCollectionNames() db.getLastError() - just returns the err msg string db.getLastErrorObj() - return full status object db.getLogComponents() db.getMongo() get the server connection object db.getMongo().setSlaveOk() allow queries on a replication slave server db.getName() db.getProfilingLevel() - deprecated db.getProfilingStatus() - returns if profiling is on and slow threshold db.getReplicationInfo() db.getSiblingDB(name) get the db at the same server as this one db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSlaveReplicationInfo()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj: 1}
db.serverStatus()
db.setLogLevel(level,<component>)
db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
db.setVerboseShell(flag) display extra information in shell output
db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
db.shutdownServer()
db.stats()
db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
db.version() current version of the server
db.watch() - opens a change stream cursor for a database to report on all changes to its non-system collections.
二,MongoDB CRUD Operations
不止CRUD,还讨论了 embedded document and arrays。
Collections
MongoDB集合类似于RDBMS中的数据表。 在MongoDB中,当我们在一个集合中引用它们时,它们会自动创建:
db.person.insert({ _id:100001,name:"Taanushree A S",age:10})
- 如果不存在,此命令将创建一个名为person的集合。如果存在,则仅将文档插入集合。
1. Create a Collection
语法:db.createCollection (<name>)
示例:
db.createCollection("person")
{ "ok" : 1 }
确认集合的存在:
> show collections
person
2. Create Capped Collections
capped collections
,就是固定大小的collections,支持基于插入顺序插入和检索文档的高吞吐量操作。工作方式类似于循环缓冲区:一旦集合填满了它所分配的空间,它就会覆盖集合中最老的文档,从而为新文档腾出空间。
这种特性决定了它的一些使用场景:
- 存储由大容量系统生成的日志信息。在没有索引的Capped Collections中插入文档的速度接近于将日志信息直接写入文件系统的速度。此外,内置的先入先出属性在管理存储使用时维护事件的顺序。
- 在一个Capped Collections中缓存少量数据。 由于读取缓存而不是写入大量缓存,因此需要确保此集合始终保留在工作集中(即在RAM中)。
Capped Collections的一些限制:
- 无法对Capped Collections进行分片。
- 不能使用聚合管道运算符
$out
来将结果写入Capped Collections。 - 无法从Capped Collections中删除文档。
- 创建索引可高效执行更新操作。
语法:db.createCollection (<name>,{capped:<boolean>,size:<number>,max :<number>})
- 如果size字段小于或等于4096,则集合的大小为size字节。否则,MongoDB将提高所提供的大小,使其成为256的整数倍。
- max表示允许的最大文件数。
例子:
> db.createCollection("student",{ capped: true,size:1000,max:2})
{ "ok" : 1 }
> db.student.isCapped()
true
可继续插入数据进行特征测试,此处我略了。
Create Operations
Create Operations可以将文档插入到集合中。 这些插入操作针对单个集合。 在单个文档级别,所有写操作都是原子的。
Insert Documents
语法:db.collection.insertOne()
或db.collection.insertMany()
或db.collection.insert()
示例:Insert a Single Document
> db.person.insertOne({ _id:1001,name:"Taanushree AS",age:10})
{ "acknowledged" : true, "insertedId" : 1001 }
- insertOne()返回包含新插入的文档的文档
_id
。如果未指定_id字段,则MongoDB会生成一个_id字段,其中包含一个ObjectId
值。 _id字段充当主键。
> db.person.insertOne({ name:"Aruna MS",age:14})
{
"acknowledged" : true,
"insertedId" : ObjectId("5f64da530dc4211a1b87073c")
}
示例:Insert Multiple Documents
> db.person.insertMany([{ _id:1003,name:"Anba V M",age:16},{ _id:
... 1004,name:"shobana",age:44}])
{ "acknowledged" : true, "insertedIds" : [ 1003, 1004 ] }
db.collection.insert()单条多条都能插入,用的比较多。
Read Operations
MongoDB提供了find()
方法来查询文档。
Query Documents
语法:db.collection.find()
- pretty()让结果更美观。
示例:Select All Documents in a collection
> db.person.find({ })
{ "_id" : 1001, "name" : "Taanushree AS", "age" : 10 }
{ "_id" : ObjectId("5f64db2a0dc4211a1b87073d"), "name" : "Aruna MS", "age" : 14 }
{ "_id" : 1003, "name" : "Anba V M", "age" : 16 }
{ "_id" : 1004, "name" : "shobana", "age" : 44 }
示例:Specify Equality Conditions
查询中使用表达式<field>:<value>
以过滤文档。
> db.person.find({ name:"shobana"})
{ "_id" : 1004, "name" : "shobana", "age" : 44 }
示例:Specify Conditions Using Query Operator
Query Selectors。
> db.person.find({ age:{ $gt:10}})
{ "_id" : ObjectId("5bac86dc773204ddade95819"), "name" : "Aruna MS", "age" : 14 }
{ "_id" : 1003, "name" : "Anba V M", "age" : 16 }
{ "_id" : 1004, "name" : "shobana", "age" : 44 }
示例:Specify AND Conditions
<field1>:<value1>,<field2>:<value2>
db.person.find({ name:"shobana",age:{ $gt:10}})
{ "_id" : 1004, "name" : "shobana", "age" : 44 }
示例:Specify OR Conditions
运算符$or
从集合中选择至少匹配一种条件的文档。
db.person.find( { $or: [ { name: "shobana" }, { age: { $eq:
20 } } ] } )
{ "_id" : 1004, "name" : "shobana", "age" : 44 }
Update Operations
在MongoDB中,更新操作针对单个集合。
MongoDB提供了修改运算符来修改字段值。
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
Update Operators。
Update Documents
示例:Update a Single Document
> db.student.updateOne({ name: "Joshi"},{ $set:{ "marks.english": 20}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
- _id是无法更新的。
- 这里涉及到嵌套查询
field.subfield
“marks.english”,后面会讲。
示例:Update Multiple Documents
> db.student.updateMany( { "result":"fail" }, { $set: { "marks. english": 20, "marks.maths": 20 }})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
示例:Replace a Document
通过将一个全新的文档作为第二个参数传递给db.collection.replaceOne()
,可以替换_id字段以外的文档的全部内容。
> db.student.replaceOne( { name: "John" }, { _id:1001,name:"John ",marks:{ english:36,maths:39},result:"pass"})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" :
1 }
- 文档替换中不要包括更新运算符。
- 替换时可省略_id字段,因为_id字段是不可变的。 但是,如果要包括_id字段,请使用与当前值相同的值。
Delete Operations
在MongoDB中,删除操作针对单个集合。
Delete Documents
示例:Delete Only One Document That Matches a Condition
> db.student.deleteOne({ name: "John"})
{ "acknowledged" : true, "deletedCount" : 1 }
示例:Delete All Documents That Match a Condition
> db.student.deleteMany({ name: "Jack"})
{ "acknowledged" : true, "deletedCount" : 2 }
示例:Delete All Documents from a Collection
> db.student.deleteMany({ })
{ "acknowledged" : true, "deletedCount" : 3 }
三,MongoDB Import and Export
MongoDB Import
MongoDB导入工具允许我们从JSON、CSV和TSV文件导入内容。但MongoDB导入仅支持UTF-8编码的文件。
准备一个csv文件:
c:\Sample\student.csv
_id,name,class
1,John,II
2,James,III
3,Joshi,I
导入:
> mongoimport --db student --collection students --type csv
--headerline --file c:\Sample\student.csv
MongoDB Export
要使用Mongo export命令,请启动mongod进程并打开另一个命令提示符以发出Mongo导出命令。
导出:
> mongoexport --db student --collection students --out C:\Sample\student.json
四,MongoDB中的嵌入式文档
用嵌入式文档可以让我们将文档嵌入另一个文档:
{ _id:1001,name:"John",marks:{ english:35,maths:38},result:"pass"}
示例:
> use employee
switched to db employee
> db.employee.insertMany([
... { _id:1001,name:"John",address:{ previous:"123,1st Main",current:"234,2nd Main"},unit:"Hadoop"},
... { _id:1002,name:"Jack", address:{ previous:"Cresent Street",current:"234,Bald Hill Street"},unit:"MongoDB"},
... { _id:1003,name:"James", address:{ previous:"Cresent Street",current:"234,Hill Street"},unit:"Spark"}
... ])
2020-09-19T01:48:53.885+0800 E QUERY [js] uncaught exception: BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: employee.employee index: _id_ dup key: { _id: 1001.0 }",
"op" : {
"_id" : 1001,
"name" : "John",
"address" : {
"previous" : "123,1st Main",
"current" : "234,2nd Main"
},
"unit" : "Hadoop"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
}) :
BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: employee.employee index: _id_ dup key: { _id: 1001.0 }",
"op" : {
"_id" : 1001,
"name" : "John",
"address" : {
"previous" : "123,1st Main",
"current" : "234,2nd Main"
},
"unit" : "Hadoop"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
BulkWriteError@src/mongo/shell/bulk_api.js:367:48
BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:332:24
Bulk/this.execute@src/mongo/shell/bulk_api.js:1186:23
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:326:5
@(shell):1:1
> db.employee.find().pretty()
{
"_id" : 1001,
"name" : "John",
"address" : {
"previous" : "123,1st Main",
"current" : "234,2nd Main"
},
"unit" : "Hadoop"
}
{
"_id" : 1002,
"name" : "Jack",
"address" : {
"previous" : "Cresent Street",
"current" : "234,Bald Hill Street"
},
"unit" : "MongoDB"
}
{
"_id" : 1003,
"name" : "James",
"address" : {
"previous" : "Cresent Street",
"current" : "234,Hill Street"
},
"unit" : "Spark"
}
Query Embedded Documents
示例: Match an Embedded or Nested Document
> db.employee.find( { address: { previous:"Cresent Street",current:"234,Bald Hill Street" }} )
{ "_id" : 1002, "name" : "Jack", "address" : { "previous" : "Cresent Street", "current" : "234,Bald Hill Street" }, "unit" : "MongoDB" }
示例:Query on a Nested Field 查询嵌套的文档内容
过滤器语法:<field.subfield>:<value>
> db.employee.find( { "address.previous": "Cresent Street" } )
{ "_id" : 1002, "name" : "Jack", "address" : { "previous" : "Cresent Street", "current" : "234,Bald Hill Street" }, "unit" : "MongoDB" }
{ "_id" : 1003, "name" : "James", "address" : { "previous" : "Cresent Street", "current" : "234,Hill Street" }, "unit" : "Spark" }
Working with Arrays
插入带有数组的数据:
> db.employeedetails.insertMany([
... { name: "John", projects: ["MongoDB", "Hadoop","Spark"],scores:[25,28,29] },
... { name: "James", projects: ["Cassandra","Spark"], scores:[26,24,23]},
... { name: "Smith",projects: [ "Hadoop","MongoDB"], scores:[22,28,26]}
... ])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5f64f61b713e47e2bf78851f"),
ObjectId("5f64f61b713e47e2bf788520"),
ObjectId("5f64f61b713e47e2bf788521")
]
}
查询所有projects中包含[“Hadoop”, “MongoDB”]这种内容与内容顺序的文档:
> db.employeedetails.find( { projects: ["Hadoop", "MongoDB"] } )
{ "_id" : ObjectId("5f64f61b713e47e2bf788521"), "name" : "Smith", "projects" : [ "Hadoop", "MongoDB" ], "scores" : [ 22, 28, 26 ] }
示例:Query an Array for an Element
> db.employeedetails.find( { projects: "MongoDB" } )
{ "_id" : ObjectId("5badcbd5f10ab299920f0728"), "name" :
"John", "projects" : [ "MongoDB", "Hadoop", "Spark" ], "scores"
: [ 25, 28, 29 ] }
{ "_id" : ObjectId("5badcbd5f10ab299920f072a"), "name" : "Smith",
"projects" : [ "Hadoop", "MongoDB" ], "scores" : [ 22, 28, 26 ] }
示例:Specify Query Operators
> db.employeedetails.find( { scores:{ $gt:26} } )
{ "_id" : ObjectId("5badcbd5f10ab299920f0728"), "name" :
"John", "projects" : [ "MongoDB", "Hadoop", "Spark" ], "scores"
: [ 25, 28, 29 ] }
{ "_id" : ObjectId("5badcbd5f10ab299920f072a"), "name" : "Smith",
"projects" : [ "Hadoop", "MongoDB" ], "scores" : [ 22, 28, 26 ] }
示例:Query an Array with Compound Filter Conditions on the Array Elements
> db.employeedetails.find( { scores: { $gt: 20, $lt: 24 } } )
{ "_id" : ObjectId("5badcbd5f10ab299920f0729"), "name" :
"James", "projects" : [ "Cassandra", "Spark" ], "scores" :
[ 26, 24, 23 ] }
{ "_id" : ObjectId("5badcbd5f10ab299920f072a"), "name" :
"Smith", "projects" : [ "Hadoop", "MongoDB" ], "scores" :
[ 22, 28, 26 ] }
示例:Using the $elemMatch operator
$elemMatch
操作符将查询结果中的<array>字段的内容限制为只包含与$elemMatch条件匹配的第一个元素。
> db.employeedetails.find({ scores: { $elemMatch: { $gt: 23, $lt: 27}} } )
{ "_id" : ObjectId("5f64f61b713e47e2bf78851f"), "name" : "John", "projects" : [ "MongoDB", "Hadoop", "Spark" ], "scores" : [ 25, 28, 29 ] }
{ "_id" : ObjectId("5f64f61b713e47e2bf788520"), "name" : "James", "projects" : [ "Cassandra", "Spark" ], "scores" : [ 26, 24, 23 ] }
{ "_id" : ObjectId("5f64f61b713e47e2bf788521"), "name" : "Smith", "projects" : [ "Hadoop", "MongoDB" ], "scores" : [ 22, 28, 26 ] }
示例:Query an Array Element by Index Position
> db.employeedetails.find( { "scores.2": { $gt: 26 } } )
{ "_id" : ObjectId("5badcbd5f10ab299920f0728"), "name" :
"John", "projects" : [ "MongoDB", "Hadoop", "Spark" ], "scores"
: [ 25, 28, 29 ] }
- 数组下标从0开始。
示例:Using the $size Operator
$size
选择指定数组大小的文档。
> db.employeedetails.find( { "projects": { $size: 2 } } )
{ "_id" : ObjectId("5badcbd5f10ab299920f0729"), "name" :
"James", "projects" : [ "Cassandra", "Spark" ], "scores" : [
26, 24, 23 ] }
{ "_id" : ObjectId("5badcbd5f10ab299920f072a"), "name" :
"Smith", "projects" : [ "Hadoop", "MongoDB" ], "scores" : [ 22,
28, 26 ] }
示例:Using the p u s h O p e r a t o r ‘ push Operator ` pushOperator‘push`添加数据到数组。
> db.employeedetails.update({ name:"James"},{ $push:{ Location: "US"}})
> db.employeedetails.find({ name:"James"})
{ "_id" : ObjectId("5c04bef3540e90478dd92f4e"), "name" :
"James", "projects" : [ "Cassandra", "Spark" ], "scores" :
[ 26, 24, 23 ], "Location" : [ "US" ] }
- 也可以像数组中添加多个数值。
> db.employeedetails.update({ name: "Smith"},{ $push:{ Location:{ $each:["US","UK"]}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.employeedetails.find().pretty()
{
"_id" : ObjectId("5f64f61b713e47e2bf78851f"),
"name" : "John",
"projects" : [
"MongoDB",
"Hadoop",
"Spark"
],
"scores" : [
25,
28,
29
]
}
{
"_id" : ObjectId("5f64f61b713e47e2bf788520"),
"name" : "James",
"projects" : [
"Cassandra",
"Spark"
],
"scores" : [
26,
24,
23
],
"Location" : [
"US"
]
}
{
"_id" : ObjectId("5f64f61b713e47e2bf788521"),
"name" : "Smith",
"projects" : [
"Hadoop",
"MongoDB"
],
"scores" : [
22,
28,
26
],
"Location" : [
"US",
"UK"
]
}
示例:Using the $addToSet Operator
$addToSet
只在集合中不存在的情况下向数组中添加元素。
> db.employeedetails.update( { name: "James"}, { $addToSet: { hobbies: [ "drawing", "dancing"]} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
示例:Using the $pop Operator
> db.employeedetails.find( { name: "James"}).pretty()
{
"_id" : ObjectId("5f64f61b713e47e2bf788520"),
"name" : "James",
"projects" : [
"Cassandra",
"Spark"
],
"scores" : [
26,
24,
23
],
"Location" : [
"US"
],
"hobbies" : [
[
"drawing",
"dancing"
]
]
}
移除scores数组中的第一个元素:
> db.employeedetails.update( { name: "James"},{ $pop:{ scores:-1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.employeedetails.find( { name: "James"}).pretty()
{
"_id" : ObjectId("5f64f61b713e47e2bf788520"),
"name" : "James",
"projects" : [
"Cassandra",
"Spark"
],
"scores" : [
24,
23
],
"Location" : [
"US"
],
"hobbies" : [
[
"drawing",
"dancing"
]
]
}
移除scores数组中的最后一个元素:
> db.employeedetails.update( { name: "James"},{ $pop: { scores:1}})
Query an Array of Embedded Documents
示例:Query for a Document Nested in an Array
准备数据:
> use student
switched to db student
> db.studentmarks.insertMany([
... { name:"John",marks:[
... { class: "II", total: 489},
... { class: "III", total: 490 }
... ]},
... { name:"James",marks:[
... { class: "III", total: 469 },
... { class: "IV",total: 450}
... ]},
... { name:"Jack",marks:[
... { class:"II", total: 489 },
... { class: "III", total: 390}
... ]},
... { name:"Smith", marks:[
... { class:"III", total: 489},
... { class: "IV", total: 490}
... ]},
... { name:"Joshi",marks:[
... { class: "II", total: 465},
... { class: "III",total: 470}
... ]}
... ])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5f64ffd1713e47e2bf788522"),
ObjectId("5f64ffd1713e47e2bf788523"),
ObjectId("5f64ffd1713e47e2bf788524"),
ObjectId("5f64ffd1713e47e2bf788525"),
ObjectId("5f64ffd1713e47e2bf788526")
]
}
> db.studentmarks.find( { "marks": { class: "II", total: 489}})
{ "_id" : ObjectId("5bae10e6f10ab299920f073f"), "name" :
"John", "marks" : [ { "class" : "II", "total" : 489 }, {
"class" : "III", "total" : 490 } ] }
{ "_id" : ObjectId("5bae10e6f10ab299920f0741"), "name" : "Jack",
"marks" : [ { "class" : "II", "total" : 489 }, { "class" :
"III", "total" : 390 } ] }
示例:Query for a Field Embedded in an Array of Documents
> db.studentmarks.find( { 'marks.total': { $lt: 400 } } )
{ "_id" : ObjectId("5bae10e6f10ab299920f0741"), "name" :
"Jack", "marks" : [ { "class" : "II", "total" : 489 }, {
"class" : "III", "total" : 390 } ] }
示例:Array Index to Query for a Field in the Embedded Document
> db.studentmarks.find( { 'marks.0.class': "II" } )
{ "_id" : ObjectId("5bae10e6f10ab299920f073f"), "name" :
"John", "marks" : [ { "class" : "II", "total" : 489 },
{ "class" : "III", "total" : 490 } ] }
{ "_id" : ObjectId("5bae10e6f10ab299920f0741"), "name" :
"Jack", "marks" : [ { "class" : "II", "total" : 489 },
{ "class" : "III", "total" : 390 } ] }
{ "_id" : ObjectId("5bae10e6f10ab299920f0743"), "name" :
"Joshi", "marks" : [ { "class" : "II", "total" : 465 },
{ "class" : "III", "total" : 470 } ] }