MongoDB -- common commands

Posted by idnoble on Tue, 25 Jan 2022 20:05:18 +0100

Xiao Huang's Mongo chapter of self-cultivation. The course video is from the dark horse programmer Click jump

There are a lot of online searches about Mongo's introduction and installation. Xiao Huang's blog is used to record how to use Mongo

The example of this article comes from the situation in reality: the article comment function will implement this example from beginning to end

MongoDB common commands

Database operation

Select, create database

The use command is used for both selection and creation. If the database exists, the database will be used. If the database does not exist, a new database will be created and used

# use database name
> use articledb
switched to db articledb

View all database commands that you have permission to view

# show dbs/databases
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> show databases
admin   0.000GB
config  0.000GB
local   0.000GB

View the database currently in use

mongo's default database is test. If you don't select a database, the collection will be placed in test

# db
> db
articledb

Introduction to system database

  • admin: from the perspective of permissions, this is the "root" database. If a user is added to the database, the user automatically inherits the permissions of all databases. Some specific server-side commands can only be run from this database, such as listing all databases or shutting down the server.
  • Local: this data will never be copied and can be used to store any collection limited to a single local server
  • Config: when Mongo is used for sharding settings, the config database is used internally to save sharding related information.

Delete database

# db.dropDatabase();
> db.dropDatabase()
{ "ok" : 1 }

Collection operation

Collections in Mongo, similar to tables in relational databases, can be created explicitly or implicitly

Explicitly create a collection (just understand)

It should be noted that the collection name must use double quotation marks to indicate that it is a string, otherwise an error will be reported: myCollection is not defined

# db. Createcollection (collection name)
> db.createCollection("myCollection")
{ "ok" : 1 }

View all collections in the current library

You can use the following two commands. Everyone likes to be lazy, and Xiao Huang is no exception. He likes to use show tables

# show tables/collections
> show tables
myCollection
> show collections
myCollection

Implicitly create a collection

When inserting a document into a collection, if the collection does not exist, the collection will be automatically created, which will be demonstrated in the next document operation

Documents in Mongo can be understood as the contents stored in relational database tables

Delete collection

Returns true if the collection is deleted successfully; otherwise, returns false

# db. Set name drop()
> db.myCollection.drop()
true
# Or use dB collection. Drop() delete
> db.collection.drop()delete
false

Document basic CRUO operation

The document is used to store data in Mongo. The data structure of the document is similar to JSON. All data stored in the collection is in BSON format, and BSON is the binary version of JSON

Document insertion

Single insert document

Use the insert and save methods to insert documents into the collection

db.Set name.insert(Document data)

Example: insert a piece of test data into the comment collection

> db.comment.insert({"articleid":"100000","content":"It's a nice day and sunny today","userid":"1001","nickname":"Rose","createdatetime":new Date(),"likenum":NumberInt(10),"state":null})
# Success will return the following information
WriteResult({ "nInserted" : 1 })

Attention

  • If the comment collection does not exist, it is implicitly created
  • Numbers in mongo are of double type by default. If you want to store integers, use NumberInt(), otherwise there will be problems with the extracted data
  • Insert current date using new Date()
  • Insert data not specified_ id, the primary key value will be automatically generated
  • If a field has no value, it can be assigned null

Batch insert document

db.Collective noun.insertMany()

Example: batch insert multiple article comments

> db.comment.insertMany([{"_id":"1","articleid":"100001","content":"We should not waste the morning on mobile phones. Health is very important. A cup of warm water is happy for you, me and him.","userid":"1002","nickname":"Forget in the Jianghu","createdatetime":new Date("2019-08-05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"},{"_id":"2","articleid":"100001","content":"I drink cold boiled water on an empty stomach in summer and warm boiled 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 always drink cold boiled water 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, which will affect your 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 that you must not drink freshly boiled water because it burns your mouth.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-08-06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"}]);
{
        "acknowledged" : true,
        "insertedIds" : [
                "1",
                "2",
                "3",
                "4",
                "5"
        ]
}

Attention

  • Specified when inserting_ id, the primary key is the value
  • If a data insertion fails, the insertion will be terminated, but the successfully inserted data will not be rolled back

Because there are a lot of batch insert data, it is easy to fail, so you can use the try catch statement to catch exceptions

try {
db.comment.insertMany([{"_id":"1","articleid":"100001","content":"We should not waste the morning on mobile phones. Health is very important. A cup of warm water is happy for you, me and him.","userid":"1002","nickname":"Forget in the Jianghu","createdatetime":new Date("2019-08-05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"},{"_id":"2","articleid":"100001","content":"I drink cold boiled water on an empty stomach in summer and warm boiled 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 always drink cold boiled water 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, which will affect your 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 that you must not drink freshly boiled water because it burns your mouth.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-08-06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"}]);
} catch (e) 
{
print (e);
}

Basic query of documents

Query data syntax is as follows

db.Set name.find(Query criteria, filter fields)

Query all

> db.comment.find()
{ "_id" : ObjectId("61ee42848d8add27409258a2"), "articleid" : "100000", "content" : "It's a nice day and sunny today", "userid" : "1001", "nickname" : "Rose", "createdatetime" : ISODate("2022-01-24T06:09:08.488Z"), "likenum" : 10, "state" : null }
{ "_id" : "1", "articleid" : "100001", "content" : "We should not waste the morning on mobile phones. Health is very important. A cup of warm water is happy for you, me and him.", "userid" : "1002", "nickname" : "Forget in the Jianghu", "createdatetime" : ISODate("2019-08-05T22:08:15.522Z"), "likenum" : 1000, "state" : "1" }
{ "_id" : "2", "articleid" : "100001", "content" : "I drink cold boiled water on an empty stomach in summer and warm boiled water in winter", "userid" : "1005", "nickname" : "She is haggard", "createdatetime" : ISODate("2019-08-05T23:58:51.485Z"), "likenum" : 888, "state" : "1" }
{ "_id" : "3", "articleid" : "100001", "content" : "I always drink cold boiled water in winter and summer.", "userid" : "1004", "nickname" : "Captain Jack", "createdatetime" : ISODate("2019-08-06T01:05:06.321Z"), "likenum" : 666, "state" : "1" }
{ "_id" : "4", "articleid" : "100001", "content" : "Experts say you can't eat on an empty stomach, which will affect your health.", "userid" : "1003", "nickname" : "Caesar", "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"), "likenum" : 2000, "state" : "1" }
{ "_id" : "5", "articleid" : "100001", "content" : "Research shows that you should never drink freshly boiled water because it burns your mouth.", "userid" : "1003", "nickname" : "Caesar", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3000, "state" : "1" }

Query by criteria

For example, I want to find information with userid 1003

> db.comment.find({userid:"1003"})
{ "_id" : "4", "articleid" : "100001", "content" : "Experts say you can't eat on an empty stomach, which will affect your health.", "userid" : "1003", "nickname" : "Caesar", "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"), "likenum" : 2000, "state" : "1" }
{ "_id" : "5", "articleid" : "100001", "content" : "Research shows that you must not drink freshly boiled water because it burns your mouth.", "userid" : "1003", "nickname" : "Caesar", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3000, "state" : "1" }

If you want to query the first data that meets this condition, use findOne

> db.comment.findOne({userid:"1003"})
{
        "_id" : "4",
        "articleid" : "100001",
        "content" : "Experts say you can't eat on an empty stomach, which will affect your health.",
        "userid" : "1003",
        "nickname" : "Caesar",
        "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"),
        "likenum" : 2000,
        "state" : "1"
}

Projection query

Sometimes we don't want to display the data of all fields, such as querying the data with userid 1003, but the query results are only displayed_ id,userid,nickname

# Where 1 stands for display and 0 stands for hiding. If you do not specify it, it defaults to 0 and the primary key defaults to 1. If you want to hide the primary key_ id:0
> db.comment.find({userid:"1003"},{userid:1,nickname:1})
{ "_id" : "4", "userid" : "1003", "nickname" : "Caesar" }
{ "_id" : "5", "userid" : "1003", "nickname" : "Caesar" }

Update of documents

Syntax for document updates

db.Set name.update(Query criteria, update data, parameters)

Document overwrite

If we want to modify the record with the primary key of 1, and change the praise amount to 1001, use the following code

> db.comment.update({_id:"1"},{likenum:NumberInt(1001)})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

At this time, when we query the record, we will find that the modified information overwrites our original information,

> db.comment.find({_id:"1"})
{ "_id" : "1", "likenum" : 1001 }

Local modification

Generally, we use local modification. This time, we modify the record with the primary key of 2 and the praise amount of 1001, using the modifier $set

> db.comment.update({_id:"2"},{$set:{likenum:NumberInt(1001)}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.comment.find({_id:"2"})
{ "_id" : "2", "articleid" : "100001", "content" : "I drink cold boiled water on an empty stomach in summer and warm boiled water in winter", "userid" : "1005", "nickname" : "She is haggard", "createdatetime" : ISODate("2019-08-05T23:58:51.485Z"), "likenum" : 1001, "state" : "1" }

Batch modification

Modify the user whose userid is 1003 and the nickname to Caesar the great

> db.comment.update({userid:"1003"},{$set{nickname:"Caesar the great"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.comment.find({userid:"1003"})
{ "_id" : "5", "articleid" : "100001", "content" : "Research shows that you must not drink freshly boiled water because it burns your mouth.", "userid" : "1003", "nickname" : "Caesar", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3000, "state" : "1" }

Looking at the modification results, we found that only one piece of information that meets the conditions has been modified. If batch modification is required, the third attribute value multi:true needs to be added

> db.comment.update({userid:"1003"},{$set:{nickname:"Caesar the great"}},{multi:true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.comment.find({userid:"1003"})
{ "_id" : "4", "articleid" : "100001", "content" : "Experts say you can't eat on an empty stomach, which will affect your health.", "userid" : "1003", "nickname" : "Caesar the great", "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"), "likenum" : 2000, "state" : "1" }
{ "_id" : "5", "articleid" : "100001", "content" : "Research shows that you should never drink freshly boiled water because it burns your mouth.", "userid" : "1003", "nickname" : "Caesar the great", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3000, "state" : "1" }

Modification of column value growth

In the actual process, the person we may browse likes it once, and we need to increase the number of likes by 1. In mongo, we need to use $inc

> db.comment.update({_id:"5"},{$inc:{likenum:NumberInt(1)}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.comment.find({_id:"5"})
{ "_id" : "5", "articleid" : "100001", "content" : "Research shows that you should never drink freshly boiled water because it burns your mouth.", "userid" : "1003", "nickname" : "Caesar the great", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3001, "state" : "1" }

remove document

db.Collective noun.remove(condition)

Delete_ Record with id 1

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

Delete all records, use with caution!!!!

db.comment.remove({})

Paging query of documents

Statistical query

Similar to count() in a relational database

db.comment.count(Query criteria, additional options)

Count all records

> db.comment.count()
4

Count records by conditions

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

Paging query

You can use limit to read a specified amount of data and skip a specified amount of data using the skip method

db.Set name.find().limit(number).skip(number)

Two items on one page to query the data on the first page

> db.comment.find().limit(2)
{ "_id" : "2", "articleid" : "100001", "content" : "I drink cold boiled water on an empty stomach in summer and warm boiled water in winter", "userid" : "1005", "nickname" : "She is haggard", "createdatetime" : ISODate("2019-08-05T23:58:51.485Z"), "likenum" : 888, "state" : "1" }
{ "_id" : "3", "articleid" : "100001", "content" : "I always drink cold boiled water in winter and summer.", "userid" : "1004", "nickname" : "Captain Jack", "createdatetime" : ISODate("2019-08-06T01:05:06.321Z"), "likenum" : 666, "state" : "1" }

Two items on one page, query the data on the second page

> db.comment.find().limit(2).skip(2)
{ "_id" : "4", "articleid" : "100001", "content" : "Experts say you can't eat on an empty stomach, which will affect your health.", "userid" : "1003", "nickname" : "Caesar the great", "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"), "likenum" : 2000, "state" : "1" }
{ "_id" : "5", "articleid" : "100001", "content" : "Research shows that you should never drink freshly boiled water because it burns your mouth.", "userid" : "1003", "nickname" : "Caesar the great", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3001, "state" : "1" }

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.Set name.find().sort(sort order)

Query by userid in descending order and likenum in ascending order

> db.comment.find({},{userid:1,likenum:1}).sort({userid:-1},{likenum:1})
{ "_id" : "2", "userid" : "1005", "likenum" : 888 }
{ "_id" : "3", "userid" : "1004", "likenum" : 666 }
{ "_id" : "4", "userid" : "1003", "likenum" : 2000 }
{ "_id" : "5", "userid" : "1003", "likenum" : 3001 }

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.

More queries for documents

Regular complex conditional query

The fuzzy query of MongoDB is realized by regular expression

db.Set name.find({field:/regular expression /})

Example: query all documents with boiled water in comments

> db.comment.find({content:/boiling water/})
{ "_id" : "2", "articleid" : "100001", "content" : "I drink cold boiled water on an empty stomach in summer and warm boiled water in winter", "userid" : "1005", "nickname" : "She is haggard", "createdatetime" : ISODate("2019-08-05T23:58:51.485Z"), "likenum" : 888, "state" : "1" }
{ "_id" : "3", "articleid" : "100001", "content" : "I always drink cold boiled water in winter and summer.", "userid" : "1004", "nickname" : "Captain Jack", "createdatetime" : ISODate("2019-08-06T01:05:06.321Z"), "likenum" : 666, "state" : "1" }

Example: query documents starting with experts in comments

> db.comment.find({content:/^expert/})
{ "_id" : "4", "articleid" : "100001", "content" : "Experts say you can't eat on an empty stomach, which will affect your health.", "userid" : "1003", "nickname" : "Caesar the great", "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"), "likenum" : 2000, "state" : "1" }

Comparison query

In practice, the greater than less than operator is also very common

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

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: query the documents whose userid field in the comment collection does not contain 1003 and 1004

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

Conditional join query

use a n d or and or and or

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)}}]})

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} }]}

Topics: Database MongoDB