Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A complete Collection of mongo statements

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

I. basic sentence

1. Create a database and view the current database

> use wang

> db

two。 View the version of the database

> db.version ()

3. Delete database

> use wang

> db.dropDatabase ()

4. Insert document

> db.test.insert ({id: 1, "name": "wangchongyang", "age": 19, "hobby": "read"})

5. Update document

> db.test.update ({id:1}, {$set: {id: 11}})

6. Delete document

> db.test.remove ({id: 11})

7. Query document

> db.test.find ()

> db.test.findOne ()

> db.test.find ({id: 11})

8. Document sorting

> db.test.find (). Sort (). Sort ({"id": 1}) 1 ascending,-1 descending

9. Create an index

> db.test.ensureIndex ({id: 1}) 1 creates the index in ascending order-1 descending order

10. Delete index

> db.test.dropIndex (id)

11. Polymerization

> db.test.aggregate ({$group: {_ id: "name", num: {$num: 1})

twelve。 Backup and recovery

Mongodump-h 127.0.0.1 tmp/mongo_backup 27017-d test-o / tmp/mongo_backup

Mongorestore-d test / tmp/mongo_backup/*

13. Remove duplicate data

> db.test.distinct ('name')

II. Collective sentence guidance

1. View collection help

Db.test.help ()

two。 View the total number of collections

Db.test.count ()

3. View tablespace size

Db.test.dataSize ()

4. View the database where the collection is located

Db.test.getDB ()

5. View the current collection status

Db.test.stats ()

6. Collection renaming

Db.test.renameCollection ("testdb")

7. Delete a collection

Db.testdb.drop ()

8. View all collections of the current database

Db.getCollectionNames ()

9. View the status of all collections

Db.printCollectionStats ()

10. Existing tables and data add fields

Db.test.update ({}, {$set: {nFlagState:0}}, false, true)

11. View the current number of connections

Db.serverStatus () connections

Third, copy and fragment statements

1. Configure a Replica Sets mode shard in the mongodb cluster and initialize the

Config = {_ id: 'shard4', members: [

{_ id: 0, host: '10.181.49.224pur27001'}

{_ id: 1, host: '10.181.49.221pur27002'}

{_ id: 2, host: '10.181.49.222pur27003'}]

}

Rs.initiate (config)

two。 Add a shard to the cluster

Db.runCommand ({addshard: "shard4/10.181.49.224:27001,10.181.49.221:27002,10.181.49.224:27002", name: "shard2"})

3. View shard information

Db.runCommand ({listshards:1})

4. Use a library with shard

Db.runCommand ({enablesharding: "okooo"})

5. View the status of replica set

Rs.status ()

State field description

0Starting up, phase 11Primary2Secondary3Recovering4Fatal error5Starting up, phase 26Unknown state7Arbiter8Down

Heath field description

0Server is down1Server is up

6. Check to see if the replica set is the master node

Rs.isMaster ()

7. View the data synchronization status of the current database

Db.printReplicationInfo ()

8. View the synchronization status of the entire shard

Db.printSlaveReplicationInfo ()

9. Currently running process

Db.currentOp ()

10. Look at the database information

Db.stats ()

11. Look at the data instance information

Db.serverStatus ()

twelve。 (execute on the master library) add a slave library

Rs.add ("192.168.8.226 purl 27004")

13. (executed on the master library) reduce one slave library

Rs.remove ("192.168.8.226 purl 27004")

14. Look at the state of the watch

Db.users.stats ()

15. Look at the shard status

Db.printShardingStatus ()

Db.printShardingStatus (true)

16. Shard existing tables

Db.runCommand ({shardcollection: "test.users_2", key: {_ id:1}})-- users_2 table is partitioned according to _ id key

17. Remove a shard

Db.runCommand ({"removeshard": "localhost:20002"})

18. Support queries from the library

Db.getMongo () .setSlaveOk ()

19. View slow query

Db.system.profile.find ()

20. Open profile

There are two ways to open profile

One is directly set in the startup parameters, and you can add-- profile= level when you start MongoDB.

The other is the db.setProfilingLevel (level, seconds) after the call from the customer server, but this only affects this session.

21. Enable sharding

Db.adminCommand ({"enableSharding": "blog"}) builds sharding on the blog library

twenty-two。 Establish sharding by using date and author fields on the posts table on blog library

Db.adminCommand ({shardCollection: "blog.posts", key: {"date": 1, "author": 1}})

IV. User management

The default startup of MongoDB is not to verify the user name and password. After starting MongoDB, you can connect directly with MongoDB and have root permissions for all libraries. So specify parameters at startup to prevent client access and connection.

To enable the login verification module of the system first, you only need to specify the auth parameter at startup, such as:

[root@template] # mongod-- auth

[root@template ~] # mongo

MongoDB shell version: 2.6.0

Connecting to: test

>

At the very beginning, MongoDB has an admin database by default (the default is empty), and admin.system.users will hold more user information than the user rights set in other databases.

Note: when no user is added to admin.system.users, even if the-auth parameter is added when MongoDB starts, if you add a user to the database except admin, you can still use any operation without any authentication until you know that you have added a user to admin.system.users.

1. Set up system root users

> show dbs

Admin (empty)

Local 0.078GB

> use admin

Switched to db admin

> db.createUser ({user: "gyw", pwd: "123456", roles: [{role: "root", db: "admin"}]})

Successfully added user: {

"user": "gyw"

"roles": [

{

"role": "root"

"db": "admin"

}

]

}

> show dbs

2016-07-29T09:19:32.668+0800 listDatabases failed: {

"ok": 0

"errmsg": "not authorized on admin to execute command {listDatabases: 1.0}"

"code": 13

} at src/mongo/shell/mongo.js:47

Failed to prompt for no permission

Log in to the database again by authentication

Mongo-- port 27017-u gyw-p 123456-- authenticationDatabase admin

MongoDB shell version: 2.6.0

Connecting to: 127.0.0.1:27017/test

> use admin

Switched to db admin

> db.system.users.find ()

{"_ id": "admin.gyw", "user": "gyw", "db": "admin", "credentials": {"MONGODB-CR": "871b1cf91cd1ebb7acf0f4040af47979"}, "roles": [{"role": "root", "db": "admin"}]}

two。 Create a single database maximum privilege user

> use test

Switched to db test

> db.test.insert ({id:1,name: "mi"})

WriteResult ({"nInserted": 1})

> db.createUser ({user: "wjb", pwd: "123456", roles: [{role: "dbOwner", db: "test"}]})

Successfully added user: {

"user": "wjb"

"roles": [

{

"role": "dbOwner"

"db": "test"

}

]

}

> use admin

Switched to db admin

> db.system.users.find ()

{"_ id": "admin.gyw", "user": "gyw", "db": "admin", "credentials": {"MONGODB-CR": "871b1cf91cd1ebb7acf0f4040af47979"}, "roles": [{"role": "root", "db": "admin"}]}

{"_ id": "test.wjb", "user": "wjb", "db": "test", "credentials": {"MONGODB-CR": "3ec31d8a58e61f450c5988b546dfde4b"}, "roles": [{"role": "dbOwner", "db": "test"}]}

We don't have the authority to authenticate and log in to see if we can access the test database.

[root@template 27017] # mongo-- port 27017

MongoDB shell version: 2.6.0

Connecting to: 127.0.0.1:27017/test

Error while trying to show server startup warnings: not authorized on admin to execute command {getLog: "startupWarnings"}

> use test

Switched to db test

> show collections

2016-07-29T09:26:17.440+0800 error: {

"$err": "not authorized for query on test.system.namespaces"

"code": 13

} at src/mongo/shell/query.js:131

You can find a hint that we don't have permission.

Log in through permission authentication

[root@template 27017] # mongo-- port 27017-u wjb-p 123456-- authenticationDatabase test

MongoDB shell version: 2.6.0

Connecting to: 127.0.0.1:27017/test

Error while trying to show server startup warnings: not authorized on admin to execute command {getLog: "startupWarnings"}

> use test

Switched to db test

> show collections

System.indexes

Test

The system built-in role name is listed below:

Database User Roles normal user role

Read

ReadWrite

Database Administration Roles Administrator role

DbAdmin can manage the database

Maximum permissions for dbOwner single database, dbAdmin,userAdmin

UserAdmin can manage current database users

Cluster Administration Roles Administrator role

ClusterAdmin

ClusterManager

ClusterMonitor

HostManager

Backup and Restoration Roles backup and recovery roles

Backup

Restore

All-Database Roles all database roles

ReadAnyDatabase is established under admin and can read the information of all databases.

ReadWriteAnyDatabase is established under admin and can read and write information from all databases.

UserAdminAnyDatabase is established under admin and can manage users of all databases.

DbAdminAnyDatabase is established under admin and can manage the information of all databases (similar to dbAdmin accounts of all databases)

Superuser Roles ()

Root

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report