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

MongoDb basic command

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

Some basics forget to check at any time.

# standby recovery

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

# backing up oplog based on time

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

# restore oplog to a 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 search

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

Use local

Db.oplog.rs.find ()

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

For (var iSuppli 0nisu Admin (switch to create user)

-> db.TestDb (create database)

-> db.addUser ("userName", "Pwd") create users

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

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

-> showcollections to check whether the table is created successfully

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

-> db.TableName.find () check whether the added data is successful (if no results are found, the addition failed)

Create a database

Grammar

The syntax format for MongoDB to create a database is as follows:

Use DATABASE_NAME

Note: this command only temporarily creates the database in memory. If no write operation exits after creation, it will be released in memory.

Delete database

Grammar

The syntax format for MongoDB to delete a database is as follows:

Db.dropDatabase ()

Note: be sure to use database before deleting the library

Insert document

MongoDB inserts a document into the collection using the insert () or save () method, with the following syntax:

Db.COLLECTION_NAME.insert ({document})

MongoDB updates the document

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

Update () method

The update () method is used to update existing documents. The syntax format is as follows:

Db.collection.update (, {upsert:, multi:, writeConcern:})

Parameter description:

Query: the query condition of update, similar to that after where in a sql update query.

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

Upsert: optional, this parameter means that if there is no record of update, whether to insert objNew,true is insert, default is false, do not insert.

Multi: optional. Mongodb defaults to false. Only the first record found is updated. If this parameter is true, multiple records are checked out according to the condition and all of them are updated.

WriteConcern: optional, the level at which the exception is thrown.

Save () method

The save () method replaces an existing document with an incoming document. The syntax format is as follows:

Db.collection.save (, {writeConcern:})

MongoDB deletes a document

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

It is a good habit to execute the find () command before executing the remove () function to determine whether the condition is correct.

Grammar

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

Db.collection.remove (, {justOne:, writeConcern:})

Parameter description:

Query: (optional) conditions for deleted documents.

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

WriteConcern: (optional) the level at which the exception is thrown.

Query document

Grammar

The syntax format 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 an easy-to-read way, you can use the pretty () method, which has the following syntax format:

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

Comparison of MongoDB and RDBMS Where statements

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

Equals {:} db.col.find ({"by": "xywydba"}) .pretty () where by = 'xywydba'

Less than {: {$lt:} db.col.find ({"likes": {$lt:50}}) .pretty () where likes

< 50 小于或等于 {:{$lte:}} db.col.find({"likes":{$lte:50}}).pretty() where likes 50 大于或等于 {:{$gte:}} db.col.find({"likes":{$gte:50}}).pretty() where likes >

= 50

Not equal to {: {$ne:} db.col.find ({"likes": {$ne:50}}) .pretty () where likes! = 50

Operation

Format

Example

Similar statements in RDBMS

MongoDB AND condition

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

The syntax format 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 format is as follows:

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

MongoDB Limit and Skip method

MongoDB Limit () method

If you need to read a specified number of data records in MongoDB, you can use MongoDB's Limit method, and 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 the specified amount of data, and the skip method also accepts a numeric parameter as the number of skipped records.

Grammar

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

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

MongoDB sorting

MongoDB sort () method

In MongoDB, you use the sort () method to sort the data, and the sort () method can specify the sorted field by parameter and use 1 and-1 to specify how to sort, where 1 is ascending sort 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

Aggregate in MongoDB is mainly used to process data (such as statistical average, summation, etc.) and return the calculated data results. It is somewhat similar to count (*) in the sql statement.

Aggregate () method

The method of aggregation in MongoDB uses aggregate ().

Grammar

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

> db.COLLECTION_NAME.aggregate (AGGREGATE_OPERATION)

The following table shows some aggregate expressions:

Expression.

Description

Example

The sum of $sum calculation. 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 for all documents in the collection. Db.mycol.aggregate ([{$group: {_ id: "$by_user", num_tutorial: {$max: "$likes"}])

Push inserts values into an array in the result document. Db.mycol.aggregate ([{$group: {_ id: "$by_user", url: {$push: "$url"}])

AddToSet inserts values into an array in the result 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 sort of resource documents. Db.mycol.aggregate ([{$group: {_ id: "$by_user", first_url: {$first: "$url"}])

$last obtains the last document data db.mycol.aggregate according to the sorting of resource documents ([{$group: {_ id: "$by_user", last_url: {$last: "$url"}])

The concept of pipeline

Pipes are commonly used in Unix and Linux to use the output of the current command as a parameter to the next command.

MongoDB's aggregation pipeline passes the results of the MongoDB document to the next after one pipe has finished processing. Pipe operations can be repeated.

Expression: processes the input document and outputs it. Expressions are stateless and can only be used to evaluate documents for the current aggregation pipeline, not 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, or to create calculation results and nested documents.

Match: used to filter data and output only documents that meet the criteria. Match uses MongoDB's standard query operation.

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

Skip: skips the specified number of documents in the aggregation pipeline and returns the remaining documents.

Unwind: splits an array type field in a document into multiple strips, each containing a value in the array.

$group: groups the documents in the collection and can be used to count the results.

$sort: sort the input documents and output them.

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

Pipe operator instance

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 instance

Db.article.aggregate ({$skip: 5})

MongoDB common commands

1. Compare with Mql

MySQL

MongoDB

Description

Mysqld

Mongod

Server daemon

Mysql

Mongo

Client tool

Mysqldump

Mongodump

Logical backup tool

Mysql

Mongorestore

Logical recovery tool

Db.repairDatabase ()

Repair the 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

Display a list of libraries

Show tables

Show collections

Show list of tables

Show slave status

Rs.status

Query master-slave status

Create table users (an int, b int)

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

Size:100000}) another: tables can be created implicitly.

Create a tabl

Create INDEX idxname ON users (name)

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

Create an index

Create INDEX idxname ON users (name,ts DESC)

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

Create an index

Insert into users values (1,1)

Db.users.insert ({aVl1, bRV 1})

Insert record

Select a, b from users

Db.users.find ({}, {aVl1, bRV 1})

Query table

Select * from users

Db.users.find ()

Query 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}, {aRom 1, BRV 1})

Conditional query

Select * from users where age33 and age30

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 the duplicate value

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 zonal 3

Db.users.find ({zvas 3}) .explain ()

Get storage path

Update users set axi1 where baggage Q'

Db.users.update ({bbure1}, {$set: {av 1}}, false, true)

Update record

Update users set a=a+2 where baked goods Q'

Db.users.update ({bju inc: {av 2}}, false, true)

Update record

Delete from users where z = "abc"

Db.users.remove ({zoren\ ABCC'})

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 ()

Delete table / collection

Db.addUser ('test',' test')

Add user

ReadOnly-- > false

Db.addUser ('test',' test', true)

Add user

ReadOnly-- > true

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

Change password

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

Or db.removeUser ('test')

Delete user

Db.system.users.find ()

View a list of users

Show users

View all users of the current library

Db.printCollectionStats ()

Check 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 collection data

Db. Users.totalIndexSize ()

Query the size of the index

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