1 introduction of directing

1.1 Storage data analysis

  1. Large amount of data
  2. Write frequently
  3. Lower value

For such data, MongoDB is more suitable for data storage

1.2 What is MongoDB

  • MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications.

  • MongoDB is a product between relational database and non-relational database. Among non-relational databases, it has the most rich functions and is the most like relational database. It supports a very loose data structure in the JSON-like Bson format, so it can store complex data types.

1.3 mongo characteristics

  • The biggest feature of Mongo is that it supports a very powerful query language, its syntax is somewhat similar to object-oriented query language, almost can achieve the majority of functions similar to relational database single table query, but also supports the establishment of indexes to data.

It is characterized by high performance, easy deployment, easy use, and very convenient data storage. The main features are:

  1. Collective-oriented storage, easy to store object type data.
  2. Pattern freedom.
  3. Supports dynamic query.
  4. Full index support, including internal objects.
  5. Supports query.
  6. Supports replication and failover.
  7. Use efficient binary data storage, including large objects (such as videos).
  8. Automatically handles fragmentation to support cloud level extensibility.
  9. Support RUBY, PYTHON, JAVA, C++, PHP, C# and other languages.
  10. The file is stored in BSON (an extension of JSON).

1.5 MongoDB architecture

  • The logical structure of MongoDB is a hierarchical structure. It is mainly composed of three parts: document, collection and database. The logical structure is user-oriented and is used by users to develop applications with MongoDB.
  1. MongoDB documents are equivalent to a row of records in a relational database.
  2. Multiple documents form a collection, which is equivalent to a table in a relational database.
  3. Multiple collections, logically organized together, are called databases.
  4. A single MongoDB instance supports multiple databases.

The hierarchical structure of document, collection and database is shown as follows:

1.6 MongoDB Data type

Special note:

1. ObjectId

ObjectId, like a unique primary key, can be quickly generated and sorted. It contains 12 bytes and has the following meanings:

  • The first four bytes represent the creation of a Unix timestamp, Greenwich Mean TIME (UTC), 8 hours later than Beijing time
  • The next three bytes are the machine id
  • The next two bytes comprise the PID from the process ID
  • The last three bytes are random numbers

Documents stored in MongoDB must have an _ID key. The value of this key can be any type, and the default is an ObjectId object

2. The timestamp

BSON has a special timestamp type that is unrelated to the normal date type. The timestamp value is a 64-bit value. Among them:

  • The first 32 bits are a time_t value [number of seconds off Unix Epoch (January 1, 1970)]
  • The last 32 bits are an increasing ordinal number operating in a given second

Within a single Mongod instance, the timestamp value is usually unique.

Date of 3.

Represents the number of milliseconds from the current Unix epoch (January 1, 1970). Date types are signed, with negative numbers indicating dates prior to 1970.

2 Basic MongoDB usage

2.1 Common Commands

1. Select and create a database

Select and create database syntax format:

Use Database nameCopy the code

View database:

show dbs
Copy the code

To view the collection, select the database first, then view the collection of the database:

show collections
Copy the code

2. Insert and query documents

After selecting the database, use collections to manipulate the document, inserting the document syntax format:

Db. Set name. Insert (data);Copy the code

Insert the following test data:

db.comment.insert({content:"Beginner",userid:"1011"})
Copy the code

Query collection syntax format:

Db.collection name.find ()Copy the code

To query all documents in the spit collection, type the following command:

db.comment.find()
Copy the code

The document will have a field called _ID, which is the primary key of the table in our original relational database. If you do not specify this field when inserting a document record, MongoDB will automatically create one of the ObjectID types. If we specify this field when inserting a document record, it can be of type ObjectID or any of the types supported by MongoDB.

Enter the following test statement:

db.comment.insert({_id:"1",content:"Why did it go wrong?",userid:"1012",thumbup:2020});
db.comment.insert({_id:"2",content:"Working late at night.",userid:"1013",thumbup:1023});
db.comment.insert({_id:"3",content:"What should I do if MY cell phone is overloaded?",userid:"1013",thumbup:111});
db.comment.insert({_id:"4",content:"Persistence is victory.",userid:"1014",thumbup:1223});
Copy the code

To query a record with userid 1013, add a parameter to find() in json format as follows:

db.comment.find({userid:'1013'})
Copy the code

To return only the first data that meets the criteria, we can use the findOne command to do this:

db.comment.findOne({userid:'1013'})
Copy the code

Returns the specified number of records. Limit can be called after find, for example:

db.comment.find().limit(2)
Copy the code

3. Modify or delete the document

Modify the syntax structure of the document:

Db. Collection name. Update (condition, modified data)Copy the code

To change the likes of the record whose id is 1 and whose likes are 1000, enter the following statement:

db.comment.update({_id:"1"},{thumbup:1000})
Copy the code

Upon execution, the document is missing except for the thumbup field.

To solve this problem, we need to use the modifier $set. The command is as follows:

db.comment.update({_id:"2"}, {$set:{thumbup:2000}})
Copy the code

Delete the syntax structure of the document:

Db. Set name. Remove (condition)Copy the code

The following statement can delete all data. Use ~ with caution

db.comment.remove({})
Copy the code

Delete criteria can be placed in braces, for example, to delete thumbup 1000, enter the following statement:

db.comment.remove({thumbup:1000})
Copy the code

4. Count the number of items

Statistical record conditions use the count() method. The following statement counts the number of records in the spit collection:

db.comment.count()
Copy the code

Statistics by condition, for example, the number of records whose userID is 1013:

db.comment.count({userid:"1013"})
Copy the code

5. Fuzzy query

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

/ Fuzzy query string /Copy the code

Query all documents whose comments contain “traffic” as follows:

Db.com ment. Find (/} {the content: / flow) `Copy the code

Query comments that begin with “overtime” with the following code:

Db.com ment. Find ({the content: / /} ^ overtime)Copy the code

6. Greater than or equal to less than or equal to

The <, <=, >, >= operator is also commonly used and has the following format:

Db. Collection name. Find ({"field" : { $gt: value}}) // Greater than: field > value db. Collection name. find({"field" : { $lt: value}}) // Less than: field < value db. Collection name. find({"field" : { $gte: value}}) // Greater than or equal to: field >= value db. Collection name. find({"field" : { $lte: value}}) // Less than or equal to: field <= value db. Collection name. find({"field" : { $ne: value}}) // does not equal: field! = valueCopy the code

Query the number of comment likes greater than 1000:

db.comment.find({thumbup:{$gt: 1000}})Copy the code

7. Inclusion and exclusion

Includes the use of the $in operator

Select * from userID where userID = 1013 and 1014;

db.comment.find({userid:{$in: ["1013"."1014"]}})
Copy the code

The use of the $nin operator is not included

Select * from userID where userID does not contain 1013 and 1014;

db.comment.find({userid:{$nin: ["1013"."1014"]}})
Copy the code

8. Conditional join

If we want a query to satisfy more than two conditions, we need to use the $and operator to correlate the conditions (equivalent to AND in SQL). Format for:

$and:[{condition},{condition},{condition}]Copy the code

Query for documents whose thumbup is greater than or equal to 1000 and less than 2000 in the comment collection:

db.comment.find({$and:[ {thumbup:{$gte:1000}} ,{thumbup:{$lt:2000} }]})
Copy the code

If the relationship between more than two conditions is or, we use the operator to make the association, which is the same as the previous use of and, in the format:

$or:[{condition},{condition},{condition}]Copy the code

Select * from comment set where userID 1013 or likes < 2000;

db.comment.find({$or:[ {userid:"1013"} ,{thumbup:{$lt:2000} }]})
Copy the code

9. Column values grow

To add or subtract a column value from its original value, use the $inc operator:

db.comment.update({_id:"2"}, {$inc:{thumbup:1}})
Copy the code

3 Common apis

1. Modify a single field

We are going to explain some of the more common ones, but the rest of the syntax is the same

/ / 1. Use$setTo modify the document based on the query criteria, to specify the value of a key, or to create it if it does not exist. db.orders.update( {"onumber" : "001"},  
   { $set: { "cname " : "zcy"}},false, // multi set totrue, all updatestrue) / / 2.$mulMultiply the value of this field by the specified value {$mul: { field: <number> } }  
db. orders.update(                            
{"ino" : "001"},  
{ $mul: {"quantity":3}}) // 3.$setOnInsertDb.collection.update (<query>, {$setOnInsert: { <field1>: <value1>, ... } },  
   {upsert: true }  
) 

db.products.update(  
      {"ino" : "001"},  
      {  
        $set: {"quantity": 3}.$setOnInsert: {"defaultQty":100 }  
      },  
      {upsert: true})$inc, specifies the value of the property plus the current value, or creates the key if it does not exist. {$inc: { <field1>: <amount1>,<field2>: <amount2>, ... } }  

db. orders.update(                            
{"onumber" : "001"."items.ino":"001"},  
{ $inc: {"items.$.price": 2.0}})Copy the code

2. Modify the array

1. Modify the embedded document (level 2) according to the query conditions. For example, we want to change the items field ino to 4 of price under 001 and change 8 of the syntax items

Example:

db. orders.update(                            
{"onumber" : "001"."items.ino":"001"},  
{ $set: {"items.$.price": 8.0}})Copy the code

For example, we want to change the items field ino to products under 001 and the pName value of pno to ps, syntax items.0.products. Updates the first matching subdocument in the array. ]

db. orders.update(                            
{"onumber" : "001"."items.ino":"001"."items.products.pno":"001"},  
{ $set: {"items.0.products.$.pName": "ps"}})Copy the code

$pop deletes the first or last item in the array

{ $pop: { <field>: <-1 | 1>,... Db.orders. Update ({db.orders.update ());"onumber" : "001"},  
{ $pop: {"items"1}}) : -Copy the code

4. $push adds a value to the array. If an array exists, add the value to the end of the array; if not, create the array and save the value

{ $push: { <field1>: <value1>,... } }  

db.orders.update({
  "onumber": "001"
}, {
  $push: {
    "items": {
      "ino": "002"."quantity": 2."price": 6.0."products": [{
          "pno": "003"."pName": "p3"
        },
        {
          "pno": "004"."pName": "p4"}}}})Copy the code

5. Delete data

Db.collection.remove () // 1. Truncate db.orders.remove({}) // 2. Remove db.orders. Remove ({db.orders."onumber": "001"}) // 3. Delete set, index not exist. db.collection.drop()Copy the code