MongoDB maintains common commands

Source: Internet
Author: User
Tags mongodump mongorestore

One, user operation:
1. #进入数据库admin
Use admin
2. #增加或修改用户密码
Db.adduser (' name ', ' pwd ')
3. #查看用户列表
Db.system.users.find ()
4. #用户认证
Db.auth (' name ', ' pwd ')
5. #删除用户
Db.removeuser (' name ')
6. #查看所有用户
Show Users
7. #查看所有数据库
Show DBS
8. #查看所有的collection
Show collections
9. #查看各collection的状态
Db.printcollectionstats ()
Ten. #查看主从复制状态
Db.printreplicationinfo ()
#修复数据库.
Db.repairdatabase ()
#设置记录profiling, 0=off 1=slow 2=all
Db.setprofilinglevel (1)
#查看profiling.
Show profile
#拷贝数据库
Db.copydatabase (' mail_addr ', ' mail_addr_tmp ')
#删除collection.
Db.mail_addr.drop ()
#删除当前的数据库
Db.dropdatabase ()
17. Backing Up the database
Mongodump-h localhost:27017-d Dataname-o/data/dump
18. Recovering a Database
Mongorestore-d Dataname/data/dump
19. Backing Up Database tables
Mongodump-h localhost:27017-d dataname-c Tablename-o/data/dump
20. Recovering a database table
Mongorestore-d dataname-c Tablename/data/dump
Mongorestore-h host:port-d dataname--collection tablename./tmpdump/some.bson

Second, data manipulation:

1. #存储嵌套的对象
Db.foo.save ({' name ': ' Ysz ', ' address ': {' city ': ' Beijing ', ' Post ': 100096}, ' phone ': [138,139]})
2. #存储数组对象
Db.user_addr.save ({' Uid ': ' [email protected] ', ' Al ': [' [email protected] ', ' [email protected] ']})
3. #根据query条件修改, insert if not present, allow multiple records to be modified
Db.foo.update ({' yy ': 5},{' $set ': {' xx ': 2}},upsert=true,multi=true)
4. Records of #删除yy =5
Db.foo.remove ({' yy ': 5})
5. #删除所有的记录
Db.foo.remove ()
6. #增加索引: 1 (Ascending), -1 (Descending)
7. Db.foo.ensureIndex ({firstname:1, lastname:1}, {unique:true});
8. #索引子对象
9. Db.user_addr.ensureIndex ({' Al.em ': 1})
Ten. #查看索引信息
Db.foo.getIndexes ()
Db.foo.getIndexKeys ()
#根据索引名删除索引.
Db.user_addr.dropIndex (' al.em_1 ')

Third, the query operation:


1. #查找所有
2. Db.foo.find ()
3. #查找一条记录
4. Db.foo.findOne ()
5. #根据条件检索10条记录
6. Db.foo.find ({' msg ': ' Hello 1 '}). Limit (10)
7. #sort排序
8. Db.deliver_status.find ({' From ': ' [email protected] '}). Sort ({' Dt ',-1})
9. Db.deliver_status.find (). Sort ({' Ct ': -1}). Limit (1)
Ten. #count操作
Db.user_addr.count ()
#distinct操作, query the specified column to repeat
Db.foo.distinct (' msg ')
# ">=" action
Db.foo.find ({"timestamp": {"$gte": 2}})
#子对象的查找
Db.foo.find ({' address.city ': ' Beijing ')
Conditional operator
$GT: >
$LT: <
$gte: >=
$lte: <=
$ne:! =, <>
$in: In
$nin: Not in
$all: All
$not: Anti-match (1.3.3 and later)

Query name <> "Bruce" and age >= 18 data
Db.users.find ({name: {$ne: "Bruce"}, Age: {$gte: 18}});

Query creation_date > ' 2010-01-01 ' and creation_date <= ' 2010-12-31 ' data
Db.users.find ({creation_date:{$gt: new Date (2010,0,1), $lte: new Date (2010,11,31)});

Querying for data in the age (20,22,24,26)
Db.users.find ({age: {$in: [20,22,24,26]}});

Query age modulo 10 equals 0 of data
Db.users.find (' this.age% 10 = = 0 ');
Or
Db.users.find ({age: {$mod: [10, 0]}});

Match all
Db.users.find ({favorite_number: {$all: [6, 8]}});
Can query out {name: ' David ', age:26, Favorite_number: [6, 8, 9]}
Can not query out {name: ' David ', age:26, Favorite_number: [6, 7, 9]}

Query mismatch name=b* lead record
Db.users.find ({name: {$not:/^b.*/}});
Query age modulo 10 is not equal to 0 data
Db.users.find ({age: {$not: {$mod: [10, 0]}}});

#返回部分字段
Choose to return the Age and _id fields (the _id field will always be returned)
Db.users.find ({}, {age:1});
Db.users.find ({}, {age:3});
Db.users.find ({}, {age:true});
Db.users.find ({name: "Bruce"}, {age:1});
0 is false, not 0 is true

Choose to return the age, address, and _id fields
Db.users.find ({name: "Bruce"}, {age:1, address:1});

Exclude return age, address, and _id fields
Db.users.find ({}, {age:0, address:false});
Db.users.find ({name: "Bruce"}, {age:0, address:false});

Number of array elements
For {name: ' David ', age:26, Favorite_number: [6, 7, 9]} record
Match Db.users.find ({favorite_number: {$size: 3}});
Mismatch Db.users.find ({favorite_number: {$size: 2}});

$exists determine if a field exists
Querying all records that exist in the name field
Db.users.find ({name: {$exists: true}});
Query all records that do not exist in the phone field
Db.users.find ({phone: {$exists: false}});

$type Judging field types
Query all name fields are of character type
Db.users.find ({name: {$type: 2}});
Query all age fields are integral type
Db.users.find ({age: {$type: 16}});

For character fields, you can use regular expressions
Query all records that lead with the letter B or B
Db.users.find ({name:/^b.*/i});

$elemMatch (1.3.1 and above)
Match one of these elements in an array field

JavaScript queries and $where queries
Check the records for age > 18 and the following queries are all the same
Db.users.find ({age: {$gt: 18}});
Db.users.find ({$where: "This.age > 18"});
Db.users.find ("This.age > 18");
f = function () {return this.age > Db.users.find} (f);

Sorting sort ()
With age ascending ASC
Db.users.find (). Sort ({age:1});
Descending desc by age
Db.users.find (). Sort ({Age:-1});

Limit the number of records returned ()
Returns 5 Records
Db.users.find (). Limit (5);
Return 3 records and print information
Db.users.find (). Limit (3). ForEach (user) {print (' my age is ' + user.age)});
Results
My age is 18
My age is 19
My age is 20

Limit the start point of the return record Skip ()
Starting from 3rd record, return 5 records (limit 3, 5)
Db.users.find (). Skip (3). Limit (5);

Number of query record bars count ()
Db.users.find (). Count ();
Db.users.find ({age:18}). Count ();
The following return is not 5, but the number of records in the user table
Db.users.find (). Skip (. Limit (5). Count ();
If you want to return the number of records after the limit, use count (true) or count (not 0)
Db.users.find (). Skip (. Limit (5). Count (True);

Grouping group ()
Suppose the test table has only one of the following data
{domain: "www.mongodb.org"
, Invoked_at: {d: "2009-11-03", T: "17:14:05"}
, response_time:0.05
, http_action: "Get/display/docs/aggregation"
}
Use the Group Statistics test table November Data count:count (*), Total_time:sum (Response_time), Avg_time:total_time/count;
Db.test.group (
{cond: {"INVOKED_AT.D": {$gt: "2009-11", $lt: "2009-12"}}
, key: {http_action:true}
, initial: {count:0, total_time:0}
, Reduce:function (Doc, out) {out.count++; Out.total_time+=doc.response_time}
, Finalize:function (out) {out.avg_time = Out.total_time/out.count}
} );

[
{
"Http_action": "Get/display/docs/aggregation",
"Count": 1,
"Total_time": 0.05,
"Avg_time": 0.05
}
]

Four: Daily Maintenance Management:
1. #查看collection数据的大小

Db.deliver_status.dataSize ()
* View Colleciont Status

Db.deliver_status.stats ()

3. #查询所有索引的大小

Db.deliver_status.totalIndexSize ()

Five, MongoDB service maintenance needs to know:

1,mongod parameter Description
--dbpath #指定db文件存放的目录
--port #指定mongod服务使用的端口
--fork #设置mongo服务为后台运行
--logpath #指定log文件的目录和文件名
--logappend #设置每次log添加在文件最后
--rest #关闭rest API Features
--nohttpinterface #关闭web管理功能
--auth #指定mongo使用身份验证机制
--bindip #用逗号分隔ip地址 used to specify
--f #将所有前面介绍的参数都可以存放到一个配置文件中, and then use this parameter to invoke the configuration file to start
2,mongodb Shutdown Method:
A. Db.shutdownserver () #推荐优先使用
B. Ctrl + C #在不使用--fork parameters can be used, may cause data file corruption
C. Use of Kill/kill-2 #在无法使用 A and B may result in data file corruption
D. kill-9 #不在万不得已的情况下, do not use this method

3. View MongoDB Status
A.db.runcommand ({"Serverstatus": 1})
B.mongo_home/bin/mongostat

4. Add user, switch user to make--auth parameter effective
Db.adduser ("root", "123")
Db.adduser ("Read_Only", "123", true); #第3个参数表示设置readonly的状态

Db.auth ("Read_Only", "123")

5. Database backup
4 ways to back up a database
A. After you close the Mongod service, copy the data file specified by the--dbpath parameter. The advantage speed is fast, the disadvantage needs to stop MONGO service.
B. Export data using Mongodump and import data with Mongorestore. The advantage does not need to stop the MONGO service, the disadvantage is that the data inserted by the user during Mongodump operation may not be backed up.
C. Fsync and lock Lock the database so that users can only use the Read feature, and then use method B to export and import data. The advantage does not need to stop the MONGO service, the disadvantage is that users cannot perform insert operations during database lock.
D. Use Slavedb and use method C to lock the Slavedb, and then use method B to export and import the data. The advantage does not need to stop the MONGO service and does not affect user insert operations (this method is recommended).

6. Repairing the database
There are 3 ways to repair a data file when the database file is compromised
A. Mongo_home/bin/mongod--repair
B. Use test
Db.repairdatabase ()
C. Db.runcommand ({"RepairDatabase": 1});

7.MongoDB loses data in an alarming way
Here http://coolshell.cn/articles/5826.html has a detailed, worth attention.

Six, MongoDB distributed cluster operations

viewing cluster shard Information
Db.printshardingstatus ()



MongoDB maintains common commands

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.