The most complete basic course of mongodb

Time:2021-5-8

MongoDB

Create database

-Format: Use Database_ NAME
    - use ruochen
    - db

Creating a database requires inserting a piece of data to be displayed in the list

-DB. Ruochen. Insert ({name ':'ruochen'})
    - show dbs

Delete database

  • Format: db.dropdatabase ()

    • use ruochen
    • db.dropDatabase()
    • show dbs

Create collection

-Format: db.createcollection (name, options)
-Name: the name of the collection to be created
-Options: optional parameter to specify the memory size and index options
field type describe
capped Boor (optional) if true, creates a fixed collection. A fixed set is a set with a fixed size. When the maximum value is reached, it will automatically cover the earliest documents.The size parameter must be specified when the value is true.
autoIndexId Boor (optional) if true, automatically_ The ID field creates an index. The default is false.
size numerical value (optional) specifies a maximum value in kilobytes (KB) for the fixed set.If capped is true, you also need to specify this field.
max numerical value (optional) specifies the maximum number of documents in the fixed collection.

When inserting a document, mongodb first checks the size field of the fixed set, and then the max field

example
#Creating Ruochen set in test database
use test
db.createCollection('ruochen')
#View existing collections
show collections

DB. Createcollection ('test ', {capped: true, autoindexid: true, size: 1024000, Max: 10000}) # autoindexid is discarded, default_ ID add index

#When you insert a document, mongodb automatically creates the collection
db.ruochen.insert({'name': 'ruochen'})

Delete collection

  • Format: dB. Collection. Drop ()

    • use ruochen
    • DB. Createcollection (‘ruochen ‘) #
    • show tables
    • db.ruochen.drop()
    • show tables

Insert document

  • Format: db.collection_ NAME.insert(document)

    • Method 1
    • DB. Ruochen. Insert ({Title: ‘mongodb tutorial’,

    description: ‘shu ju ku’,
    by: ‘ruochen’,
    tags: [‘mongodb’, ‘database’, ‘NoSQL’]
    })

    • db.ruochen.find()
    • Method 2
    • document=({title: ‘mongodb’,

    description: ‘shu ju ku’,
    by: ‘ruochen’,
    tags: [‘mongodb’, ‘database’, ‘NoSQL’]
    })

    • db.ruochen.insert(document)
    • db.ruochen.find()
  • DB. Collection. Insertone()? Inserts a document data into the specified collection
  • DB. Collection. Insertmany() # inserts multiple document data into the specified collection

    • var document = db.ruochen.insertOne({“e”: 3})
    • document
    • var res = db.ruochen.insertMany([{‘a’: 1}, {‘b’: 2}])
    • res
  • Insert multiple data at once

    • Create an array first
    • Put the data in the data
    • Insert into the collection once
    • case

      • var arr = [];
      • for(var i = 1; i < 5; i++){
        arr.push({num:i});}
      • db.num.insert(arr);

Update document

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

Query: the query conditions of the update are similar to those after where in the SQL update query
Update: the object of the update and some Update Operators (such as $, $Inc...) can also be understood as the object after set in the SQL update query
Upert: optional. This parameter means whether to insert objnew if there is no update record. True means insert. The default is false and no insert
Multi: optional. Mongodb is false by default. Only the first record found will be updated. If this parameter is true, all the records found by the condition will be updated
Writeconcern: optional, the level of exception thrown

case
db.ruochen.insert({
    title: 'mongodb',
    Description: 'NoSQL database',
    by: 'ruochen',
    tags: ['mongodb', 'databases', 'NoSQL']
})

DB. Ruochen. Update ({title ':'mongodb'}, {$set: {title ':'mongodb'}) # only the first discovered document will be modified
db.ruochen.find().pretty()

db.ruochen.update({'title': 'mongodb'}, {$set:{'title': 'MongoDB'}}, { multi:true }) # modify multiple identical documents


Save() method: replace the existing document with the passed in document
format
db.collection.save(
    <document>,
    {
        writeConcern: <document>
    }
)
Document: document data
Writeconcern: optional, the level of exception thrown

case
db.ruochen.save({
    "_id" : ObjectId("5e631a14c17b253e9cef40cc"),
    "title" : "MongoDB",
    "Description": "mongodb is a NoSQL database,",
    "by" : "Runoob",
    "url" : "http://www.runoob.com",
    "tags" : [
            "mongodb",
    ]
})
db.ruochen.find().pretty()

remove document

Grammar:
db.collection.remove(
    <query>,
    <justOne>
)

Syntax format after version 2.6
db.collection.remove(
    <query>
    {
        justOne: <boolean>,
        writeConcern: <document>
    }
)

Parameter description
Query: (optional) the condition of the deleted document
Justone: (optional) if it is set to true or 1, only one document will be deleted. If this parameter is not set or the default value of false is used, all documents matching the criteria will be deleted
Writeconcern: (optional) the level at which the exception was thrown

db.ruochen.remove({'title': 'mongodb'})

#Delete only the first record found
db.COLLECTION_NAME.remove(DELETION_CRITHRIA, 1)

#Delete all data
db.ruochen.remove({})
db.ruochen.find()

#The remove () method does not really free up space
#You need to execute dB. Repairdatabase() to reclaim disk space
db.repairDatabase()
db.runCommand({repairDatabase: 1})

The remove method is out of date
#Delete all documents in the collection
db.ruochen.deleteMany({})
#Delete all documents with num equal to 1
db.ruochen.deleteMany({num: '1'})
#Delete a document with num equal to 1
db.ruochen.deleteOne({num: '1'})

consult your documentation

Grammar:
db.collection.find(query, projection)
Parameter description
Query: optional, use the query operator to specify the query conditions
Projection: optional, use the projection operator to specify the returned key. When querying, all the key values in the document are returned. Just omit the parameter (omitted by default)

#Read data in an easy to read way
db.ruochen.find().pretty()
operation format example Similar statements in RDBMS
be equal to {key:value} db.ruochen.find({‘by’:’ruochen’}).pretty() where by = ‘ruochen’
less than {key:{$lt: value}} db.ruochen.find({‘likes’: {$lt:3}}).pretty() where likes < 3
Less than or equal to {key:{$lte: value}} db.ruochen.find({‘likes’: {$lte:2}}).pretty() where likes <= 2
greater than {key:{$gt: value}} db.ruochen.find({‘likes’: {$gt:100}}).pretty() where likes > 100
Greater than or equal to {key:{$gte: value}} db.ruochen.find({‘likes’: {$gte:200}}).pretty() where likes >= 200
Not equal to {key:{$ne: value}} db.ruochen.find({‘likes’: {$ne:200}}).pretty() where likes != 200

And condition

  • The find () method can pass in multiple keys separated by commas, which is the and condition of normal SQL
  • Format:

    • db.ruochen.find({key1: value1, key2: value2}).pretty()
  • case

    • db.ruochen.find({‘by’: ‘ruochen’, ‘likes’: 200}).pretty()

It is similar to where by Ruochen ‘and likes = 200

Or condition

  • format

    db.ruochen.find(
        {
            $or:[
                {key1: value1}, {key2: value2}
            ]
        }
    ).pretty()
    
  • case

    • db.ruochen.find({$or:[{‘likes’: 2}, {‘likes’:200}]}).pretty()

Union of and and or

  • db.ruochen.find({‘likes’: {$gt:100}, $or: [{‘likes’: 2}, {‘likes’: 200}]}).pretty()

Conditional Operator

db.ruochen.insert({
    title: 'python',
    description: 'i love python',
    by: 'ruochen',
    url: 'xxx',
    tags: ['python'],
    likes: 200
})

db.ruochen.insert({
    title: 'php',
    Description: 'PHP is the best language in the world',
    by: 'ruochen',
    url: 'xxx',
    tags: ['php'],
    likes: 150
})

db.ruochen.insert({
    title: 'MondoDB',
    Description: 'NoSQL database',
    by: 'ruochen',
    url: 'xxx',
    tags: ['mongodb'],
    likes: 100
})

#Get the data with 'likes' greater than 100 in the' Ruochen 'set
db.ruochen.find({likes: {$gt: 100}}).pretty()
#Similar to SQL statements
Select * from ruochen where likes > 100;


Get the data with 'likes' greater than or equal to 100 in the' Ruochen 'set
db.ruochen.find({likes: {$gte: 100}}).pretty()
#Similar to SQL statements
Select * from ruochen where likes >= 100;


#Get the data with 'likes' less than 150 in the' Ruochen 'set
db.ruochen.find({likes: {$lt: 150}}).pretty()
#Similar to SQL statements
Select * from ruochen where likes < 150;


#Get the data whose 'likes' is less than or equal to 150 in the' Ruochen 'set
db.ruochen.find({likes: {$lte: 150}}).pretty()
#Similar to SQL statements
Select * from ruochen where likes <= 150;

Mongodb uses (<) and (>) queries – $LT and $GT

  • Get the data of “likes” greater than 100 and less than 200 in “Ruochen” set

    • db.ruochen.find({likes: {$lt: 200, $gt: 100}}).pretty()
    • Similar to SQL statement

      • Select * from ruochen where likes > 100 and likes < 200;

Fuzzy query

  • Query the document with ‘py’ in the title

    • db.ruochen.find({title:/py/}).pretty()
  • Query documents whose title field begins with ‘p’

    • db.ruochen.find({title:/^p/}).pretty()
  • Query documents whose title field ends with ‘p’

    • db.ruochen.find({title:/p$/}).pretty()

Mongodb $type operator

  • The $type operator is based on the bson type to retrieve the matching data types in the collection and return the results
type number remarks
Double 1  
String 2  
Object 3  
Array 4  
Binary data 5  
Undedined 6 obsolete
Object id 7  
Boolean 8  
Date 9  
Null 10  
Regular Experssion 11  
JavaScript 13  
Symbol 14  
JavaScript(with scope) 15  
32-bit integer 16  
Timestamp 17  
64-bit integer 18  
Min key 255 Query with -1
Max key 127  
  • Get the data with the title of string in the “Ruochen” collection

    • db.ruochen.find({‘title’: {$type: 2}}).pretty()
    • db.ruochen.find({‘title’: {$type: String}}).pretty()

Limit and skip methods

Limit() method

  • Read the specified number of data records in mongodb, and use the limit method of mongodb
  • The limit() method takes a numeric parameter that specifies the number of records to read from mongodb
  • grammar

    • db.COLLECTION_NAME.find().limit(NUMBER)
  • case

    • db.ruochen.find().limit(2)

Skip() method

  • The skip () method skips the specified amount of data
  • The skip method takes a numeric parameter as the number of records to skip
  • grammar

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

    • db.ruochen.find().limit(1).skip(1)

The default parameter of skip() method is 0

Mongodb sorting

  • Sort() method

    • The sort () method can specify the fields to be sorted by parameters, and use 1 and – 1 to specify the sorting method, where 1 is ascending and – 1 is descending
    • grammar

      • db.COLLECTION_NAME.find().sort({key: 1})
    • case

      • The data in the Ruochen set is arranged in descending order of the fields like
      • db.ruochen.find().sort({‘likes’: -1}).pretty()

When skip(), limit(), sort() are executed together, the order of execution is sort(), then skip(), and finally limit().

Mongodb index

  • Create index() method

    • Mongodb uses the createindex () method to create an index
    • grammar

      • db.collection.createIndex(keys, options)
      • The key value is the index field you want to create, 1 is to create the index in ascending order, and – 1 is to create the index in descending order
    • case

      • db.ruochen.createIndex({‘title’: 1})
      • DB. Ruochen. Createindex ({title ‘: 1,’ description ‘: – 1}) # set multiple fields to create an index

Createindex() receives optional parameters. The list of optional parameters is as follows

Parameter Type Description
background Boolean The process of creating an index will block other database operations. Background can specify how to create an index in the background mode, that is, add the optional parameter “background”“ Background “the default value isfalse
unique Boolean Whether the index created is unique. Specifies that a unique index is created for true. The default value isfalse
name string The name of the index. If not specified, mongodb generates an index name by connecting the field name and sort order of the index
dropDups Boolean Version 3.0 + is obsolete. To delete duplicate records when creating a unique index, specify true to create a unique index. The default value isfalse
sparse Boolean The index is not enabled for the field data that does not exist in the document; This parameter needs special attention. If it is set to true, the document that does not contain the corresponding field will not be found in the index field. The default value isfalse
expireAfterSeconds integer Specify a value in seconds to complete TTL setting and set the lifetime of the set
v index version The version number of the index. The default index version depends on the version mongod runs when it creates the index
weights document The index weight value, which is between 1 and 99999, indicates the score weight of the index relative to other index fields
default_language string For text indexing, this parameter determines the list of stop words and rules for stemming and lexicographers. The default is English
language_override string For text index, this parameter specifies the name of the field to be included in the document. The default language is overridden by the language, and the default value is language

Mongodb aggregation

  • Mongodb aggregate is mainly used to process data (such as system level average, sum, etc.) and return calculated data results. It’s a bit like count (*) in SQL statements

Aggregate() method

  • grammar

    • db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
  • example

    • db.ruochen.aggregate([{$group: {_id: “$by”, num_tutorial: {$sum: 1}}}])
    • Similar to an MQL statement

      • select by, count(*) from ruochen group by by

Aggregate expression

expression describe example
$sum Calculate the sum db.ruochen.aggregate([{$group: {_id: “$by”, num_tutorial: {$sum: “$likes”}}}])
$avg average value db.ruochen.aggregate([{$group: {_id: “$by”, avg: {$avg: “$likes”}}}])
$min Gets the minimum value of all documents in the collection db.ruochen.aggregate([{$group: {_id: “$by”, min: {$min: “$likes”}}}])
$max Gets the maximum value of all documents in the collection db.ruochen.aggregate([{$group: {_id: “$by”, min: {$max: “$likes”}}}])
$push Inserts values into an array in the result document db.ruochen.aggregate([{$group: {_id: “$by”, url: {$push: “$url”}}}])
$addToSet Inserts values into an array in the result document, but does not create a copy db.ruochen.aggregate([{$group: {_id: “$by”, url: {$addToSet: “$url”}}}])
$first Get the first document data according to the sorting of resource documents db.ruochen.aggregate([{$group: {_id: “$by”, url: {$first: “$url”}}}])
$last Get the last document data according to the sorting of resource documents db.ruochen.aggregate([{$group: {_id: “$by”, url: {$last: “$url”}}}])

The Conduit

  • Pipeline is generally used in UNIX and Linux to take the output of the current command as the parameter of the next command
  • The aggregation pipeline of mongodb transfers the results of mongodb documents to the next pipeline after processing by one pipeline
  • Pipeline operations are repeatable
  • Expressions: process documents and output

    • The expression is stateless and can only be used to calculate the document of the current aggregation pipeline, not to process other documents
  • Common operations

    • $project: modify the structure of the input document. It can be used to rename, add, or delete fields, as well as to create calculation results and nested documents
    • $match: used to filter data and output only qualified documents$ Match uses the standard query operation of mongodb
    • $limit: used to limit the number of documents returned by 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 the document into multiple fields, each containing a value in the array
    • $group: group the documents in the collection, which can be used for statistical results
    • $sort: sort the input documents and output them
    • $geonear: output ordered documents close to a certain geographical location

give an example

  • $project

    db.ruochen.aggregate(
        { $project: {
            title: 1,
            by: 1,    
        }}
    );
    There's only one left_ ID, title and by are three fields, which are the default_ The ID field is contained
    
    db.ruochen.aggregate(
        { $project: {
            _id: 0
            title: 2,
            by: 1,    
        }}
    );
    In this way, it can be excluded_ ID, non-zero can indicate the display field, negative number can also indicate the display field
  • $match

    Get the records with score greater than 70 or less than or equal to 90, and then send the qualified records to the next stage $group pipeline operator for processing
    db.ruochen.aggregate([
        {$match: {score: {$gt: 70, $lte: 90}}},
        {$group: {_id: null, count: {$sum: 1}}}
    ])

When the match condition and group exist at the same time, the order will affect the retrieval results, so the match must be written first

  • $skip

    Filter the top 5 documents
    db.ruochen.aggregate(
        {$skip: 5});