MongoDB Common Commands
From Kiinlam
Installation
MongoDB official website Download installation (Windows installation method)
Basic knowledge
Collections-Tables in the corresponding relational database
Documents--correspond to rows in a relational database
Start the database service
After locating in the Bin folder in the installation directory
> mongod --dbpath ../data/db
If you don't have data/db
a folder, you need to create it to dbpath
specify where the data is stored
Open a Client Access database
Execute under the same Bin folder
> mongo
Connect to database by default test
Show Help
> help
Show all database names
> show dbs
Switch database
> use test
Displays the database name of the current connection
> db
Display all collections of the current database
> show collections
Show the methods supported by the database
> db.help()
Show supported Methods for collections
> db.users.help()
Create a Collection
> db.createCollection("users")
Inserting action Insert
> db.users.insert({"name":"kiinlam","age":28})
Query operations find Find all documents
> db.users.find()
Find the specified document
> db.users.find({"name":"kiinlam"})
Query A
> db.users.findOne({"name":"kiinlam"})
Greater than $GT
> db.users.find({"age":{$gt:22}})
Greater than or equal to $gte
> db.users.find({"age":{$gte:22}})
Less than $LT
> db.users.find({"age":{$lt:22}})
Less than or equal to $gte
> db.users.find({"age":{$lte:22}})
Not equal to $ne
> db.users.find("age":{$ne:22})
or $or
> db.users.find({$or:[{"name":"kiinlam"},{"name":"cheungkiinlam"}]})
$in in the collection
> db.users.find("name":{$in:["kiinlam","cheungkiinlam"]})
Not $nin in collection
> db.users.find("name":{$nin:["kiinlam","cheungkiinlam"]})
Regular queries
> db.users.find({"name":/^k/,"name":/m$/})
Filter Query $where
// 使用js function作为筛选条件> db.users.find({$where: function(){return this.name==‘kiinlam‘}})
Limiting the number of queries limit
> db.users.find({"age":22}).limit(10)
Update action updates Specifies that the document is all updated, equal to overwrite
> db.users.update({"name":"kiinlam"}, {"name":"cheungkiinlam","age":27})
Partial update One: Incremental update $inc
// age增加2,其他不变> db.users.update({"name":"kiinlam"}, {$inc:{"age":2}})
Partial update two: Field modification $set
// age改为20> db.users.update({"name":"kiinlam"}, {$set:{"age":20}})
New update: If it doesn't exist, add a new one
// 第三个参数为true> db.users.update({"name":"kiinlam"}, {$set:{"age":18}}, true)
Batch Update
// 如果匹配多条,默认只改第一条,将第四个参数设为true可全部更新> db.users.update({"name":"kiinlam"}, {$set:{"age":18}}, true, true)
Save Operation Save
// 插入新文档,如果不提供"_id"字段> db.users.save({"name":"kiinlam", "age":28})// 更新已存在的文档> db.users.save({"_id":"xxx","name":"kiinlam", "age":28})
Remove Operation Remove
Delete Operation not recoverable
Delete all but do not delete the index
> db.users.remove({})
Delete the specified document
> db.users.remove({"name":"kiinlam"})
Deletes a specified document, if there are multiple results
> db.users.remove({"name":"kiinlam"}, true)
Completely delete the collection, including the index, you should use thedrop
When a large number of deletions are made, copy the documents that need to be persisted to the new collection, and then drop
delete the collection.
Deleting a database
> db.dropDatabase()
Delete Collection
> db.users.drop()
Count Operation Count
> db.users.count()> db.users.count({"age":29})
Unique value query distinct specifies that the field has multiple simultaneous, one-to-many, and returns an array of the values of the specified field
> db.users.distinct("age")
Group Operations Group
age
grouped results are stored in user
, and the value is an array of corresponding age
name values, as per the grouping operation
key
: Group on
initial
: Initialize function, each different age group shares the same function
$reduce
: The first parameter is the current document, the second parameter is the cumulative object of the previous function operation, and the first one is the initial
corresponding object
> db.users.group({ "key": {"age": true}, "initial": {"user": []}, "$reduce": function(cur,prev){ prev.user.push(cur.name); } })
Suppose you have the following data:
{ "_id" : ObjectId("55910457607379845607d9e2"), "name" : "kiinlam", "age" : 29 }{ "_id" : ObjectId("55910468607379845607d9e3"), "name" : "shadow", "age" : 26 }{ "_id" : ObjectId("55910992607379845607d9e5"), "name" : "foo", "age" : 29 }{ "_id" : ObjectId("55911fca607379845607d9e6"), "name" : "dd", "age" : 22 }{ "_id" : ObjectId("55911fd3607379845607d9e7"), "name" : "mm", "age" : 22 }{ "_id" : ObjectId("55911fdf607379845607d9e8"), "name" : "gg", "age" : 22 }{ "_id" : ObjectId("55911feb607379845607d9e9"), "name" : "jj", "age" : 22 }{ "_id" : ObjectId("55920545ff40738c1fd0a839"), "name" : "zz", "age" : 1 }
The result of the grouping is:
[ { "age" : 29, "user" : [ "kiinlam", "foo" ] }, { "age" : 26, "user" : [ "shadow" ] }, { "age" : 22, "user" : [ "dd", "mm", "gg", "jj" ] }, { "age" : 1, "user" : [ "zz" ] }]
More grouping features
Optional parameters: condition
and finalize
.
`condition` —— 过滤条件`finalize` —— 函数,分组完成后执行
Filter out age
documents greater than 22, add attributes to indicate the number of files in the group
> db.users.group({ "key": {"age": true}, "initial": {"user": []}, "$reduce": function(cur,prev){ prev.user.push(cur.name); }, "condition": {"age":{$lte:22}}, "finalize": function(out){ out.count = out.user.length; } })
The result of the grouping is:
[ { "age" : 22, "user" : [ "dd", "mm", "gg", "jj" ], "count" : 4 }, { "age" : 1, "user" : [ "zz" ], "count" : 1 }]
Mapreduce
map
: Mapping functions, internal calls emit(key,value)
, collections key
are grouped by mapping.
reduce
: Simplification of functions, grouping map
of data after grouping simplification, in the reduce(key,value)
key
emit
Middle key
, and value
then is emit
the collection of grouped results.
mapReduce
: The last function to execute, the parameter is map
, reduce
and some optional arguments.
> db.users.mapReducefunction ( map , reduce , optionsOrOutString ){ var c = { mapreduce : this._shortName , map : map , reduce : reduce }; assert( optionsOrOutString , "need to supply an optionsOrOutString" ) if ( typeof( optionsOrOutString ) == "string" ) c["out"] = optionsOrOutString; else Object.extend( c , optionsOrOutString ); var raw = this._db.runCommand( c ); if ( ! raw.ok ){ __mrerror__ = raw; throw Error( "map reduce failed:" + tojson(raw) ); } return new MapReduceResult( this._db , raw );}
Create a map
function
function (){ emit(this.name,{count:1});}
Create a reduce
function
function (key,value){ var result = {count:0}; for(var i = 0; i < value.length; i++){ result.count += value[i].count; } return result;}
Perform mapReduce
actions
> db.users.mapReduce(map,reduce,{"out":"collection"})
Suppose you have the following data
{ "_id" : ObjectId("55910457607379845607d9e2"), "name" : "kiinlam", "age" : 29 }{ "_id" : ObjectId("55910468607379845607d9e3"), "name" : "shadow", "age" : 26 }{ "_id" : ObjectId("55910992607379845607d9e5"), "name" : "foo", "age" : 29 }{ "_id" : ObjectId("55920545ff40738c1fd0a839"), "name" : "zz", "age" : 1 }{ "_id" : ObjectId("55911fca607379845607d9e6"), "name" : "foo", "age" : 22 }{ "_id" : ObjectId("55911fd3607379845607d9e7"), "name" : "foo", "age" : 22 }{ "_id" : ObjectId("55911fdf607379845607d9e8"), "name" : "foo", "age" : 22 }{ "_id" : ObjectId("55911feb607379845607d9e9"), "name" : "foo", "age" : 22 }
Output results
{ "result" : "collection", // 存放最终结果的集合名 "timeMillis" : 28, "counts" : { "input" : 8, // 传入文档的次数 "emit" : 8, // emit函数被调用次数 "reduce" : 1, // reduce函数被调用次数 "output" : 4 // 最后返回文档的个数 }, "ok" : 1}
To view collection
the results in a collection
> db.collection.find()
Output results
{ "_id" : "foo", "value" : { "count" : 5 } }{ "_id" : "kiinlam", "value" : { "count" : 1 } }{ "_id" : "shadow", "value" : { "count" : 1 } }{ "_id" : "zz", "value" : { "count" : 1 } }
Cursor
A cursor represents only a reference, not a real execution, and, when needed, iterates through a for loop or next()
method, and when the enumeration finishes, the cursor is destroyed and no longer returns data.
Declare a cursor
> var list = db.collection.find()
By forEach
traversing a cursor
> list.forEach(function(i){ print(i._id); })
Output results
fookiinlamshadowzz
or by next
iterating through the collection
> var list = db.collection.find()> list.next(){ "_id" : "foo", "value" : { "count" : 5 } }> list.next(){ "_id" : "kiinlam", "value" : { "count" : 1 } }> list.next(){ "_id" : "shadow", "value" : { "count" : 1 } }> list.next(){ "_id" : "zz", "value" : { "count" : 1 } }> list.next()2015-07-01T11:27:38.186+0800 E QUERY Error: error hasNext: false at Error (<anonymous>) at DBQuery.next (src/mongo/shell/query.js:255:15) at (shell):1:6 at src/mongo/shell/query.js:255> list>
Index Ensureindex Index
// 1为升序,-1为降序> db.users.ensureIndex({"name":1})
Unique index
> db.users.ensureIndex({"name":1},{"unique":true})
Combined index
> db.users.ensureIndex({"name":1, "age":-1})
View Index
> db.users.getIndexes()
Query by specified index
> db.users.find({"name":"kiinlam"}).hint({"name":1,"age":1})
Delete Index
// 删除所有自定义索引> db.users.dropIndexes()// 删除指定索引> db.users.dropIndex("name_1")
Performance analysis Function explain
> db.users.find().explain("executionStats")
Master-Slave database deployment Create primary database Master
> mongod --dbpath=XXX --master
Create a slave from a database
// 指定从数据库端口--port// 指定主数据库源--source> mongod --dbpath=XXX --port=8888 --slave --source=127.0.0.1:27017
Specify the primary database source later
> mongod --dbpath=XXX --port=8888 --slave// 后期添加源// 切换到local数据库> use local// 在sources中加入源地址> db.sources.insert({"host":"127.0.0.1:27017"})
Replica set Replset
The schema does not have a specific primary database, one database is down, and the other database is on top
Create the first database server
// 需要指定集群名及下一个数据库地址> mongod --dbpath=XXX --port 2222 --replSet mySet/127.0.0.1:3333
Create a second database server
> mongod --dbpath=XXX --port 3333 --replSet mySet/127.0.0.1:2222
Initializing a replica set
// 进入任一数据库的admin集合> mongo 127.0.0.1:2222/admin// 执行初始化操作> db.runCommand({ "replSetInitiate":{ "_id":"mySet", "members":[ { "_id":1, "host":"127.0.0.1:2222" }, { "_id":2, "host":"127.0.0.1:3333" } ] } })
Arbiter Server
// 启动仲裁服务器> mongod --dbpath=XXX --port 4444 --replSet mySet/127.0.0.1:2222// 回到admin集合中添加仲裁服务器> mongo 127.0.0.1:2222/admin> rs.addArb("127.0.0.1:4444")// 查看服务器集群状态> rs.status()
Shard Technology
Splits the collection to divide the split data over several shards.
Main players:
- Client
- Routing Server MONGOs
- Configure the server
- Shard DB Instance
Turn on Configuration server Config
> mongod --dbpath=XXX --port 2222
Turn on the routing server MONGOs
// 指定配置服务器> mongos --port 3333 --configdb=127.0.0.1:2222
Open the Shard database server Mongod
> mongod --dbpath=XXX --port 4444> mongod --dbpath=XXX --port 5555
Service configuration
// 进入mongos数据库admin集合> mongo 127.0.0.1:3333/admin// 添加分片服务器addshard> db.runCommand({ "addshard":"127.0.0.1:4444", "allowLocal":true })> db.runCommand({ "addshard":"127.0.0.1:5555", "allowLocal":true })// 开启数据库test的分片功能enablesharding> db.runCommand({"enablesharding":"test"})// 指定集合中分片的片键users.name> db.runCommand({"shardcollection":"test.users","key":{"name":1}})// 在mongos中查看数据分片情况> use test> db.printShardingStatus()
Operation and Maintenance
Operations typically involve the following 4 areas
- Installation deployment
- Status monitoring
- Security Certifications
- Backup and Recovery
Install the deployment as a Windows service
// 指定日志路径,添加install参数> mongod --dbpath=XXX --logpath=XXX --port=2222 --install// 启动服务> net start MongoDB
State Monitoring Static statistics
Db.stats ()
// 查看单个数据库状态> db.stats()
stats
Relatively simple, you can refer to the db.stats () article
Db.serverstatus ()
// 查看整个mongodb的状态// 进入admin集合> mongo 127.0.0.1:2222/admin// 查看状态> db.serverStatus()
serverStatus
A lot of parameters, you can refer to the Db.serverstatus () article
Real-time statistics
> mongostat --port 2222
Security Certifications
Todo
A little complicated, lazy, reference safety certification
Backup and Recovery
// 备份test数据库到D:\mongodb\backup> mongodump --port 2222 -d test -o D:\mongodb\backup// 恢复数据,drop表示恢复前删除原有数据> mongorestore --port 2222 -d test --drop D:\mongodb\backup
Resources
- Mongodb
- MongoDB Documentation
- Install-mongodb-on-windows
- 8-Day learning through MongoDB series
MongoDB Common Commands