MongoDB common commands

Posted by lightkeepr on Mon, 25 Oct 2021 04:58:23 +0200

Open MongoDB service with configuration file:

./mongod -f /mongodb/single/mongod.conf

/mongodb/single/mongod.conf is where the configuration file is located

Open MongoDB

mongo --host=192.168.56.101

192.168.56.101: the ip address of the remote MongoDB server is not written – port means the default port is used for login

Databases management syntax

operationgrammar
View all databasesshow dbs; Or show databases;
View current databasedb;
Switch to a database (create a database if it does not exist)use <db_name>;
Delete current databasedb.dropDatabase();

Collection management syntax

operationgrammar
View all collectionsshow collections;
Create collectiondb.createCollection("<collection_name>");
Delete collectiondb.<collection_name>.drop()

insert

  • Use dB. < collection_ Name >. Insertone() adds a document to the collection, and the parameter is a json format document
  • Use dB. < collection_ Name >. Insertmany() adds multiple documents to the collection, and the parameter is json document array
db.collection.insert({
  <document or array of documents>,
  writeConcern: <document>,
  ordered: <boolean>
})


// Add a document to the collection
db.collection.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
// Add multiple documents to the collection
db.collection.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
   { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
   { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

If a data insertion fails, the insertion will be terminated, but the successfully inserted data will not be rolled back. Because batch insertion is prone to failure due to a large amount of data, try catch can be used for exception capture processing, which can not be processed during testing. For example:

    try {
      db.aaa.insertMany([
        {"_id":"1","articleid":"100001","content":"We shouldn't waste the morning on mobile phones, Health is important, A cup of warm water happiness you, me and him.","userid":"1002","nickname":"Forget in the Jianghu","createdatetime":new Date("2019-0805T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"},
        {"_id":"2","articleid":"100001","content":"I drink cold boiled water on an empty stomach in summer, Drink warm water in winter","userid":"1005","nickname":"She is haggard","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"},
        {"_id":"3","articleid":"100001","content":"I've been drinking cold boiled water, Drink it in winter and summer.","userid":"1004","nickname":"Captain Jack","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"},
        {"_id":"4","articleid":"100001","content":"Experts say you can't eat on an empty stomach, Affect health.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"},
        {"_id":"5","articleid":"100001","content":"Research shows, Don't drink freshly boiled water, Because it burns your mouth.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-0806T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"}

    ]);

    } catch (e) {
      print (e);
    }

Query Read

  • Use dB. < collection_ The name >. Find () method queries the collection and accepts a query condition in json format. It returns an array
  • db.<collection_ Name >. Findone() queries the first qualified document in the collection and returns an object

Query + condition: select * form comment where userid =1003

db.comment.find({userid:'1003'})

Only one condition is found: limit 0,1

db.comment.findOne({userid:'1003'})

Projection

In some cases, we do not need all fields to query the document. For example, we only need id or user name. We can "project" the document

  • 1 - display
  • 0 - dont display
> db.users.find( {}, {username: 1} )

> db.users.find( {}, {age: 1, _id: 0} )

Query results are displayed only_ id,userid,nickname :

db.comment.find({userid:"1003"},{userid:1,nickname:1})

Query all data, but only display_ id,userid,nickname :

db.comment.find({},{userid:1,nickname:1})

Delete remove

Delete the syntax structure of the document:

db.Set name.remove(condition)

The following statement can delete all data. Please use it with caution

db.comment.remove({})

If deleted_ For the record with id=1, enter the following statement

db.comment.remove({_id:"1"})

Document query enhancement:

Statistical query

db.collection.count(query, options)

Parameters:

ParameterTypeDescription
querydocumentQuery selection criteria.
optionsdocumentOptional. Additional options for modifying the count.

[example]

Count all records in the comment collection:

db.comment.count()

Count the number of records with userid 1003

db.comment.count({userid:"1003"})

Paging query

You can use the limit() method to read the specified amount of data and the skip() method to skip the specified amount of data

The basic syntax is as follows:

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

If you want to return the record of the specified number, you can call limit after the fifind method to return the result (TopN), with a default value of 20, for example.

db.comment.find().limit(3)

The skip method also accepts a numeric parameter as the number of records skipped. (not for the first N), the default value is 0

db.comment.find().skip(3)

Paging query: requirement: 2 per page, starting from the second page: skip the first two pieces of data, and then display 3 and 4 pieces of data

//Page 1 db.comment.find().skip(0).limit(2) / / page 2 db.comment.find().skip(2).limit(2) / / page 3 db.comment.find().skip(4).limit(2)

Sort query

The sort() method sorts the data. The sort() method can specify the fields to be sorted by parameters and specify the sorting method by using 1 and - 1, where 1 is ascending and - 1 is descending

db.COLLECTION_NAME.find().sort({KEY:1}) or db.Set name.find().sort(sort order)

For example:

The userid s are arranged in descending order and the traffic is arranged in ascending order

db.comment.find().sort({userid:-1,likenum:1})

Tips:

When skip(), family (), sort() are executed together, the order of execution is first sort(), then skip(), and finally the displayed limit(), which is independent of the command writing order.

Regular query

The fuzzy query of MongoDB is realized by regular expression. The format is:

db.collection.find({field:/regular expression /})or db.aggregate.find({field:/regular expression /})

Tip: regular expression is the syntax of js, which is written directly.

For example, I want to query all documents with "boiled water" in the comments, and the code is as follows:

db.comment.find({content:/boiling water/})

If you want to query the content of the comment that begins with "expert", the code is as follows:

db.comment.find({content:/^expert/})

Comparison query

<, < =, >, > = this operator is also very common. The format is as follows:

db.Set name.find({ "field" : { $gt: value }}) // Greater than: field > value dB. Set name. Find ({"field": {$LT: value}}) / / less than: field < value dB. Set name. Find ({"field": {$GTE: value}}) / / greater than or equal to: field > = value dB. Set name. Find ({"field": {$LTE: value}}) / / less than or equal to: field < = value dB. Set name. Find ({"field": {$ne: value}}) / / not equal to: field= value

Example: query records with more than 700 comments and likes

db.comment.find({likenum:{$gt:NumberInt(700)}})

Include query

Contains the use of the $in operator. Example: the userid field in the collection of query comments contains 1003 or 1004 documents

db.comment.find({userid:{$in:["1003","1004"]}})

The $nin operator is not included. Example: the userid field in the query comment collection does not contain 1003 and 1004 documents

db.comment.find({userid:{$nin:["1003","1004"]}})

Conditional join query

If we need to query more than two conditions at the same time, we need to use the $and operator to correlate the conditions. The format is:

$and:[ { },{ },{ } ] 

Example: query documents with likenum greater than or equal to 700 and less than 2000 in the comment collection:

db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]})

If more than two conditions are or related, we use the operator to associate them. The same way as the previous and is used. The format is:

$or:[ { },{ },{ } ]

Example: query the document records with userid of 1003 or the number of likes less than 1000 in the comment collection

db.comment.find({$or:[ {userid:"1003"} ,{likenum:{$lt:1000} }]})

Index usage

Implementation plan

Analyze query performance usually uses an execution plan (Explain Plan) to view the query

$ db.<collection_name>.find( query, options ).explain(options)

For example: view according to user_id query data

Before adding index

"Stage": "collscan", which means full set scanning

After adding an index

"Stage": "ixscan", index based scanning

Topics: Database MongoDB