MongoDB Basic Command

Source: Internet
Author: User
Tags create index mongodb limit mongodb query mongodb update mongodump mongorestore
Some basics forgot to check at any time. .

#Ready to resume

mongodump --port 20001 --authenticationDatabase = admin -u * -d lvlv -c lvlv -o / home

mongorestore --drop --host 172.16.201.74 --port 20001 --authenticationDatabase = admin -umgbackup -d test /tmp/liding/test/liding.bson

 

#Backup oplog based on time

mongodump --port 20001 --authenticationDatabase = admin -u * -d local -c oplog.rs -q 'ts: ($ lt: Timestamp (1462830369,1), $ gt: Timestamp (1462821613, 1))}'- o / tmp / lidddd

 

#Recover oplog to temporary library

mongorestore -u * --authenticationDatabase = admin --host 172.16.201.73 --port 27017 -d local -c oplog.rs /data/backup/oplog1/local/oplog.rs.bson

 

#Replay oplog from temporary library

mongooplog --port 20001 -u * --authenticationDatabase = admin --from = 172.16.201.73: 27017

 

 

oplog lookup

db.oplog.rs.find ((ts: {$ lt: Timestamp (1462917498, 1), $ gt: Timestamp (1462918425, 1))}.

 

 

use local

 db.oplog.rs.find ()

date -d @ 1361542596 + "% Y-% m-% d% H:% M:% S"

 for (var i = 0; i <1000; i ++) {db.lvlv.save ({"xywy": i})}

 

 

 sql = "db.getReplicationInfo ();"

echo "$ sql" | /usr/local/xywy/mongodb-3.0.8/bin/mongo 127.0.0.1:20001/admin -u * -pC ^ 8cE # 1RvX5rBg0 --authenticationDatabase = admin --shell

 

Add administrative user:

 

use admin

db.createUser (

  {

    user: "*",

    pwd: "*****",

    roles: [{role: "root", db: "admin"}]

  }

)

 

Add backup user:

use admin

db.createUser (

  {

    user: "mgbackup",

    pwd: "*********",

    roles: [{role: "backup", db: "admin"}, {role: "restore", db: "admin"}]

  }

)

Add daily operations users:

use admin

db.createUser (

  {

    user: "mgadmin",

    pwd: "*****",

    roles: [{role: "readWriteAnyDatabase", db: admin}]

  }

)

 

 

Add read and write users:

 

use admin

db.createUser (

 {

   user: "liuyunsong",

   pwd: "*****",

   roles: [

      {role: "rw", db: "123"}

   ]

 }

)

 

Modify user permissions:

use admin

db.runCommand (

  {

    updateUser: "liuyaxin",

    pwd: "****",

         roles: [

    {role: "read", db: "123"}

         ]

  }

)

 

delete users:

use 123

db.dropUser ("123")

 

Delete all users under a library:

use 123

db. dropAllUsers ()

 

Add roles to users:

use 123

db.runCommand ({grantRolesToUser: "*",

                 roles: [

                    {role: "admin", db: "admin"}

                 ]

             })

 

Remove role from user:

use 123

db.runCommand ({revokeRolesFromUser: "liuyaxin",

                 roles: [

                    {role: "read", db: "234"}

                 ]

             })

Creating a Role:

use admin

db.runCommand ({createRole: "rw",

  privileges: [

    {resource: {db: "123", collection: ""}, actions: ["find", "update", "insert", "remove"]}

  ],

  roles: [

    {role: "read", db: "admin"}

  ]

})

Modify role permissions:

use admin

db.runCommand (

   {

     updateRole: "rw",

     privileges:

         [

           {

             resource: {db: "123", collection: ""},

             actions: ["find", "update", "insert", "remove"]

           }

         ],

     roles:

         [

           {role: "read", db: "admin"}

         ]

   }

)

 

Remove role:

use admin

db.runCommand (

   {

     dropRole: "rw",

     writeConcern: {w: "majority"}

   }

)

Remove all roles:

Use 123

db.runCommand (

   {

     dropAllRolesFromDatabase: 1,

     writeConcern: {w: "majority"}

   }

)

Add permissions to the role:

use 123

db.runCommand (

   {

     grantPrivilegesToRole: "rw",

     privileges: [

         {

           resource: {db: "123", collection: ""}, actions: ["find"]

         }

     ]

   }

)

Remove role permissions:

Use 123

db.runCommand (

   {

     revokePrivilegesFromRole: "rw",

     privileges:

      [

        {

          resource: {db: "123", collection: ""},

          actions: ["insert", "find"]

        }

      ]

   }

)

Refresh permissions:

Use admin

db.runCommand ({invalidateUserCache: 1})

 

1. In the database, check whether the account given by the business staff exists in the database

use database

show users

2. Authorize according to the needs of business developers

Read and write user name: library name

First define the read and write roles

use library name

db.runCommand ({createRole: "rw",

privileges: [

{resource: {db: "Library name", collection: ""}, actions: ["find", "update", "insert", "remove", "listCollections"]}

],

roles: [

]

})

Plus users

use library name

db.createUser (

{

user: "Library Name",

pwd: "*****",

roles: [

{role: "rw", db: "library name"}

]

}

)

 

Read-only user: library name_r

Define a read-only role first

use library name

db.runCommand ({createRole: "r",

privileges: [

{resource: {db: "Library name", collection: ""}, actions: ["find", "listCollections"]}

],

roles: [

]

})

Adding users

use library name

db.createUser (

{

user: "Library Name_r",

pwd: "************",

roles: [

{role: "r", db: "library name"}

]

}

)

 

 

3. Check whether the authorization is effective

Log in to the database with an authorized user and check whether the permissions of the library are correct

use library name

db.auth ("" "")

4. Send the authorized username and password to the project leader and the dba group for archiving at the same time, the format is

idc: xx master library ip: port slave library ip: port

Database

Read and write user: databases Read and write password: xxx

Read-only user: databases_r Read-only password: xxx

Administrative user: database_admin Administrative password: xxx

 

-> use Admin (switch to create user)

 

-> db.TestDb (create database)

 

-> db.addUser ("userName", "Pwd") Create user

 

-> db.auth ("userName", "Pwd") sets the user as a user allowed to connect

 

-> db.createCollection ("TableName") creates a table

 

-> showcollections to see if the table was created successfully

 

-> db.TableName.Save ({age: 1}) add data

 

-> db.TableName.find () View added data 

Whether it succeeded (if no results were found, it means that the addition failed)

 

Create database

grammar

The syntax for creating a database in MongoDB is as follows:

use DATABASE_NAME

Note: This command only temporarily creates a database in memory. If there is no write operation after creation, it will be released in memory

Delete database

grammar

The syntax of MongoDB delete database is as follows:

db.dropDatabase ()

Note: be sure to use database before deleting the library

 

Insert document

MongoDB uses insert () or save () method to insert documents into the collection, the syntax is as follows:

db.COLLECTION_NAME.insert ({document})

MongoDB update document

MongoDB uses the update () and save () methods to update documents in a collection. Let's take a closer look at the application of the two functions and their differences.

update () method

The update () method is used to update an existing document. The syntax is as follows:

db.collection.update (<query>, <update>, {upsert: <boolean>, multi: <boolean>, writeConcern: <document>})

Parameter Description:

query: update query conditions, similar to where in the sql update query.

update: update object and some update operators (such as $, $ inc ...), etc., can also be understood as the set after the sql update query

upsert: optional, this parameter means, if there is no update record, whether to insert objNew, true is inserted, default is false, not inserted

multi: Optional. By default, mongodb is false, and only the first record found is updated. If this parameter is true, all the records detected by the condition are updated.

writeConcern: Optional, the level at which the exception was thrown.

save () method

The save () method replaces an existing document with the passed in document. The syntax is as follows:

db.collection.save (<document>, {writeConcern: <document>})

MongoDB delete document

The MongoDB remove () function is used to remove data from the collection.

It is a good practice to execute the find () command to determine whether the execution conditions are correct before executing the remove () function.

grammar

The basic syntax of the remove () method is as follows:

db.collection.remove (<query>, {justOne: <boolean>, writeConcern: <document>})

Parameter Description:

query: (optional) the condition of the deleted document.

justOne: (optional) if set to true or 1, only one document is deleted.

writeConcern: (optional) The level at which the exception was thrown.

Querying documents

grammar

The syntax of MongoDB query data is as follows:

> db.COLLECTION_NAME.find ()

The find () method displays all documents in an unstructured way.

If you need to read data in a readable way, you can use pretty () method, the syntax is as follows:

> db.col.find (). pretty ()

Comparing MongoDB and RDBMS Where statements

If you are familiar with regular SQL data, you can better understand MongoDB's conditional query through the following table:

Equals {<key>: <value>} db.col.find ({"by": "xywydba"}). Pretty () where by = ‘xywydba’

Less than {<key>: {$ lt: <value>}} db.col.find ({"likes": {$ lt: 50}}). Pretty () where likes <50

Less than or equal to {<key>: {$ lte: <value>}} db.col.find ({"likes": {$ lte: 50}}). Pretty () where likes <= 50

Greater than {<key>: {$ gt: <value>}} db.col.find ({"likes": {$ gt: 50}}). Pretty () where likes> 50

Greater than or equal to {<key>: {$ gte: <value>}} db.col.find ({"likes": {$ gte: 50}}). Pretty () where likes> = 50

Not equal to {<key>: {$ ne: <value>}} db.col.find ({"likes": {$ ne: 50}}). Pretty () where likes! = 50

operating

format

example

Similar statements in RDBMS

MongoDB AND conditions

MongoDB's find () method can pass multiple keys, each key separated by a comma, and the AND condition of regular SQL.

The syntax is as follows:

> db.col.find ((key1: value1, key2: value2)). pretty ()

 

MongoDB OR condition

 

The MongoDB OR conditional statement uses the keyword $ or, and the syntax is as follows:

 

> db.col.find ({$ or: [{key1: value1}, {key2: value2}]}) .pretty ()

 

MongoDB Limit and Skip methods

MongoDB Limit () method

If you need to read a specified number of data records in MongoDB, you can use the MongoDB Limit method. The limit () method accepts a numeric parameter that specifies the number of records to read from MongoDB.

grammar

The basic syntax of the limit () method is as follows:

> db.COLLECTION_NAME.find (). limit (NUMBER)

MongoDB Skip () method

In addition to using the limit () method to read a specified amount of data, we can also use the skip () method to skip a specified amount of data. The skip method also accepts a numeric parameter as the number of records to skip.

grammar

The syntax of the skip () method script is as follows:

> db.COLLECTION_NAME.find (). limit (NUMBER) .skip (NUMBER)

 

MongoDB sort

MongoDB sort () method

In MongoDB, use the sort () method to sort the data. The sort () method can specify the sorted fields by parameters, and use 1 and -1 to specify the sorting method, where 1 is ascending order, and -1 is used for descending sort.

grammar

The basic syntax of the sort () method is as follows:

> db.COLLECTION_NAME.find (). sort ({KEY: 1})

 

MongoDB aggregation

Aggregation in MongoDB is mainly used to process data (such as statistical averages, sums, etc.) and return calculated data results. Somewhat similar to count (*) in SQL statements.

aggregate () method

The aggregate method in MongoDB uses aggregate ().

grammar

The basic syntax of the aggregate () method is as follows:

> db.COLLECTION_NAME.aggregate (AGGREGATE_OPERATION)

The following table shows some aggregated expressions:

expression

description

Examples

$ sum calculates the sum. db.mycol.aggregate ([{$ group: {_id: "$ by_user", num_tutorial: {$ sum: "$ likes"}}}))

$ avg calculates the average db.mycol.aggregate ([{$ group: {_id: "$ by_user", num_tutorial: {$ avg: "$ likes"}}}])

$ min Gets the minimum value corresponding to all documents in the collection. db.mycol.aggregate ([{$ group: {_id: "$ by_user", num_tutorial: {$ min: "$ likes"}}}))

$ max gets the maximum value corresponding to all documents in the collection. db.mycol.aggregate ([{$ group: {_id: "$ by_user", num_tutorial: {$ max: "$ likes"}}}))

$ push inserts values into an array in the resulting document. db.mycol.aggregate ([{$ group: {_id: "$ by_user", url: {$ push: "$ url"}}}])

$ addToSet inserts values into an array in the resulting document, but does not create a copy. db.mycol.aggregate ([{$ group: {_id: "$ by_user", url: {$ addToSet: "$ url"}}}))

$ first gets the first document data according to the order of the resource documents. db.mycol.aggregate ([{$ group: {_id: "$ by_user", first_url: {$ first: "$ url"}}}))

$ last gets the last document data according to the sort of resource document db.mycol.aggregate ([{$ group: {_id: "$ by_user", last_url: {$ last: "$ url"}}}))

The concept of pipes

Pipes are generally used in Unix and Linux to take the output of the current command as an argument to the next command.

MongoDB's aggregation pipeline passes MongoDB documents to the next pipeline for processing after one pipeline is processed. Pipeline operations are repeatable.

Expression: Process the input document and output. Expressions are stateless and can only be used to compute the document of the current aggregation pipeline. They cannot process other documents.

Here we introduce several operations commonly used in the aggregation framework:

$ project: Modify the structure of the input document. Can be used to rename, add, or delete fields. It can also be used to create calculation results and nest documents.

$ match: Used to filter data and output only documents that meet the conditions. $ match uses MongoDB's standard query operations.

$ limit: used to limit the number of documents returned by the MongoDB aggregation pipeline.

$ skip: Skip the specified number of documents in the aggregation pipeline and return the remaining documents.

$ unwind: Split an array type field in the document into multiple pieces, each containing one value in the array.

$ group: Groups the documents in the collection, which can be used for statistical results.

$ sort: Sort the input documents and output.

$ geoNear: Output ordered documents close to a geographic location.

Pipe operator examples

1. $ project instance

 

db.article.aggregate ({$ project: {title: 1, author: 1,}});

 

2. $ match instance

 

db.articles.aggregate ([{$ match: {score: {$ gt: 70, $ lte: 90}}}, {$ group: {_id: null, count: {$ sum: 1}})]);

3. $ skip example

db.article.aggregate ({$ skip: 5});

mongoDB commonly used commands

1.Comparison with Mql

MySQL

MongoDB

Description

mysqld

mongod

Server daemon

mysql

mongo

Client tools

mysqldump

mongodump

Logical backup tool

mysql

mongorestore

Logical Recovery Tool

 

db.repairDatabase ()

Repair database

mysqldump

mongoexport

Data export tool

source

mongoimport

Data Import Tool

grant * privileges on *. * to…

Db.addUser ()

Db.auth ()

New user and permissions

show databases

show dbs

Show library list
Show tables

Show collections

Show table list

Show slave status

Rs.status

Query the master-slave status

Create table users (a int, b int)

db.createCollection ("mycoll", {capped: true,

size: 100000}) Another: tables can be created implicitly.

Create table

Create INDEX idxname ON users (name)

db.users.ensureIndex ({name: 1})

Create index

Create INDEX idxname ON users (name, ts DESC)

db.users.ensureIndex ({name: 1, ts: -1})

Create index

Insert into users values (1, 1)

db.users.insert ({a: 1, b: 1})

Insert record

Select a, b from users

db.users.find ((), {a: 1, b: 1})

Lookup table

Select * from users

db.users.find ()

Lookup table

Select * from users where age = 33

db.users.find ({age: 33})

Conditional query

Select a, b from users where age = 33

db.users.find ({age: 33}, {a: 1, b: 1})

Conditional query

select * from users where age <33

db.users.find ({‘age‘: {$ lt: 33}})

Conditional query

select * from users where age> 33 and age <= 40

db.users.find ({‘age‘: {$ gt: 33, $ lte: 40}})

Conditional query

select * from users where a = 1 and b = ‘q’

db.users.find ({a: 1, b: ‘q‘})

Conditional query

select * from users where a = 1 or b = 2

db.users.find ({$ or: [{a: 1}, {b: 2}]})

Conditional query

select * from users limit 1

db.users.findOne ()

Conditional query

select * from users where name like "% Joe%"

db.users.find ({name: / Joe /})

Fuzzy query

select * from users where name like "Joe%"

db.users.find ({name: / ^ Joe /})

Fuzzy query

select count (1) from users

Db.users.count ()

Get the number of table records

select count (1) from users where age> 30

db.users.find ({age: {‘$ gt‘: 30}}). count ()

Get the number of table records

select DISTINCT last_name from users

db.users.distinct (‘last_name’)

Remove duplicate values

select * from users ORDER BY name

db.users.find (). sort ({name: -1})

Sort

select * from users ORDER BY name DESC

db.users.find (). sort ({name: -1})

Sort

EXPLAIN select * from users where z = 3

db.users.find ((z: 3}). explain ()

Get storage path

update users set a = 1 where b = ‘q’

db.users.update ({b: ‘q‘}, {$ set: {a: 1}}, false, true)

update record

update users set a = a + 2 where b = ‘q’

db.users.update ({b: ‘q‘}, {$ inc: {a: 2}}, false, true)

update record

delete from users where z = "abc"

db.users.remove ({z: ‘abc‘})

Delete Record

 

db. users.remove ()

Delete all records

drop database IF EXISTS test;

use test

db.dropDatabase ()

Delete database

drop table IF EXISTS test;

db.mytable.drop ()

Drop table / collection

 

db.addUser (‘test’, ‘test’)

Add user

readOnly-> false

 

db.addUser (‘test’, ’test’, true)

Add user

readOnly-> true

 

db.addUser ("test", "test222")

change the password

 

db.system.users.remove ({user: "test"})

Or db.removeUser (‘test’)

delete users

 

db.system.users.find ()

View user list

 

show users

View all users in the current library

 

db.printCollectionStats ()

View the status of each collection

 

db.printReplicationInfo ()

View master-slave replication status

 

show profile

View profiling

 

db.copyDatabase (‘mail_addr’, ’mail_addr_tmp’)

Copy database

 

db.users.dataSize ()

View the size of the collection data

 

db. users.totalIndexSize ()

Query index size

MongoDb basic 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.