MongoDBCRUD operations (focusing on update operations) (1)

Source: Internet
Author: User
Tags mongodb query

MongoDBCRUD operations (focusing on update operations) (1)
I. Introduction

MongoDB is a high-performance, open-source, and non-pattern document-based database. It is currently the most popular NoSQL database product. Data is stored in a data set by group. It is called a set (Collenction). For files stored in the MongoDB database, we do not need to know its free schema defined by any structure, when storing data, the set key of the key-value pair is a string, and the value can be any type in the data type set, including arrays and documents.

MongoDB stores all files in the set. The set is a group of documents that share public indexes. The set is similar to a table in a relational database. In MongoDB, these operations modify a single collection of data for update, delete, and delete operations. Let's first look at the MongDB structure:

MongoDB

Relational Database

Database)

Database)

Collection)

Table)

Document)

Row)

 

Collection document)

Ii. Add MongoDB

 

1. Add a new document to the set syntax

db.collection.insert()

Example:

 

  db. orders.insert({                                     "onumber" : "001",           "date" : "2015-07-02",           "cname" : "zcy",  })

 

 

Compared with SQL statements:

INSERT INTO orders                      (onumber, date, cname)      VALUES     (“001”,” 2015-07-02”,” zcy”)

2. Add multiple documents at the same time to input Arrays

 db. orders.insert( [{         "onumber" : "001",           "date" : "2015-07-02",           "cname" : "zcy",   },{         "onumber" : "002",           "date" : "2015-07-02",           "cname" : "zcy1",   }])

 

3. Add documents to include documents (level 3)

Example:

 

db. orders.insert({          "onumber" : "001",           "date" : "2015-07-02",           "cname" : "zcy",           "items" :[ {                   "ino" : "001",                  "quantity" : 2,                    "price" : 4.0,                    "products" : [                               {                                "pno":"001",                                "pName":"p1"                                },                               {                                 "pno":"002",                                 "pName":"p2"                               }                              ]             },{                "ino" : "002",               "quantity" : 2,                 "price" : 6.0,                 "products" : [                      {                           "pno":"003",                           "pName":"p3"                       },                      {                           "pno":"004",                           "pName":"p4"                       }                       ]          }   ]})

 

Note:

Each document stored in the MongoDB set has a default primary key _ id. The primary key name is fixed and can be any data type supported by MongoDB. The default value is ObjectId.

Iii. MongoDB Query

1. For the syntax of document query, we will give a brief introduction here. We will write a more detailed introduction

 

db.collection.find()

 

Query all records

2. We can query by condition

Example:

 

db.orders.find({onumber:'001'});

 

4. MongoDB Modification

 

1. syntax for modifying a document

 

db.collection.update(  
 
  ,  
  
   ,   upsert:
   
    ,   multi:
    
     )
    
   
  
 

 

Parameters

Type

Description

Query

Document

Which query conditions are to be modified, similar to the SQL where

Update

Document

Value corresponding to the field to be modified

Upsert

Boolean

Optional. The default value is false. If the corresponding document is not found according to the query conditions, if it is set to true, it is equivalent to executing insert. If it is set to false, no operation is performed.

Multi

Boolean

Optional. The default value is false. If multiple records are found based on the query conditions, if it is set to false, only the first record is modified. If it is set to true, all records are updated.

 

2. modify a single Field

Name

Description

$ Inc

Increment the value of the field according to the value to be added.

$ Mul

Multiply the value of this field by the specified value.

$ Rename

Rename a field

$ SetOnInsert

During operation, the Operation assigns a value to the corresponding field

$ Set

Specifies the value of a key. If it does not exist, it is created.

$ Unset

Specifies the value of a key. If it does not exist, it is not created.

$ Min

This field is updated only when the specified value is smaller than the existing field value.

$ Max

This field is updated only when the specified value is greater than the existing field value.

$ CurrentDate

Set the value of the current date field or as a date or timestamp.

 

We will explain several common operations, and the rest of the syntaxes are the same.

2) use $ set to modify the document according to the query conditions to specify a key value. If it does not exist, create it.

Example:

 

 db.orders.update(                             {"onumber" : "001"},   { $set: { "cname " : "zcy"} },   false,   true)

 

SQL statement. If set specifies a field to modify the value, if it does not exist, an error is returned.

 

UPDATE ordersset cname=’zcyUp’WHERE onumber=’001’

 

Before modification:

 

  db. orders.insert({                                "onumber" : "001",     "date" : "2015-07-02",})

 

After modification:

 

 

Set multi to true, update all

3) $ mul multiply the value of this field by the specified value

Syntax:

 

{ $mul: { field: 
 
   } }
 

 

Example:

 

db. orders.update(                          {"ino" : "001"},{ $mul: {"quantity" :3} })

 


Before modification:

 

db. orders.insert({                  "ino" : "001",                  "quantity": 2,                   "price" : 4.0}

 

After modification:

 

4) $ setOnInsert operation assigns values to the corresponding fields

Syntax:

 

db.collection.update(  
 
  ,   {$setOnInsert: { 
  
   : 
   
    , ... } },   {upsert: true })
   
  
 


 

Example:

 

db.products.update(  {"ino" : "001"},  {    $set:{ "quantity":3 },    $setOnInsert:{ "defaultQty":100 }  },  {upsert: true })

 


5) $ inc: add the current value to the value of the specified attribute. If the key does not exist, create it.

Syntax:

 

{ $inc: { 
 
  : ,
  
   : , ... } }
  
 

 


Example:

 

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

 

Data before modification:

 

db. orders.insert({          "onumber" : "001",           "date" : "2015-07-02",           "cname" : "zcy",           "items" :[ {                   "ino" : "001",                  "quantity" : 2,                    "price" : 4.0,                    "products" : [                               {                                "pno":"001",                                "pName":"p1"                                },                               {                                 "pno":"002",                                 "pName":"p2"                               }                              ]             },{                "ino" : "002",               "quantity" : 2,                 "price" : 6.0,                 "products" : [                      {                           "pno":"003",                           "pName":"p3"                       },                      {                           "pno":"004",                           "pName":"p4"                       }                       ]          }   ]})

 

 

 

Modified data:

 

The price of ino equal to 001 is changed to 6.

 

3. Modify the Array

 

Name

Description

$

As a placeholder for updating and querying conditions in an update first element

$ AddToSet

Add elements to the array only when they do not exist in the Set

$ Pop

Deletes the first or last entry of an array.

$ PullAll

Remove all matching values from the array

$ Pull

Removes all array elements that match the specified query.

$ PushAll

Add all values to the array

$ Push

Add a value to an array. If an array exists, add the value to the end of the array. If the array does not exist, create the array and save the value.

 

(1) modify the embedded document (level 2) in the document according to the query conditions. For example, if we want to modify the items field ino to 4 of price under 001, modify 8. Syntax: items. $. price: update the first matched sub-document in the array. Our embedded document ino is unique to meet our needs.

Example:

 

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

 

Data before modification:

 

 

Modified data:

 

The price value of ino equal to 001 is changed from 4 to 8.

The price value of ino equal to 002 remains unchanged.

(2) modify the embedded documents in the document according to the query conditions (level 3 ), for example, we want to modify the items field ino to be equal to products in 001 and pno to be equal to pName in 001 to ps. Syntax items.0.products. $. pName, 0 indicates the first array of items (I .e. the subscript of the array), and $ updates the first matched sub-document in the array.

Example:

 

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

 

Data before modification:

 

 

Modified data:

 

 

(3) $ pop deletes the first or last entry of the array.

Syntax:

 

{ $pop: { 
 
  : <-1 | 1>,... } }
 

 

1. Last item

-1 is the first item

Example:

 

db. orders.update(                          {"onumber" : "001"},{ $pop: {"items" : -1} })

 

 

Data before modification

 

 

Modified data

 

Delete ino equal to 001, with only ino 002

(4) $ push adds the value to the array. If some arrays exist, add the value to the end of the array. If the array does not exist, create the array and save the value.

Syntax:

 

 { $push: { 
 
  : 
  
   ,... } }
  
 

 

 

Example:

 

 

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

 

Data before modification:

 

 

db. orders.insert({"onumber" : "001",         "date" : "2015-07-02",         "cname" :"zcy",  "items" :[ {"ino" : "001",                  "quantity": 2,                   "price" : 4.0,                   "products" : [{   "pno":"001",  "pName":"p1"},{   "pno":"002",  "pName":"p2"}]}]})

 

Modified data:

 

$ Pull is the opposite of $ push. We will not introduce it here.

 

V. MongoDB Deletion

 

 

(1) Delete a document

Syntax

Db. collection. remove ()

 

Example:

1) db. orders. remove ({})

Delete all data in the orders set. The set still exists and the index still exists. It is equivalent to the SQL truncate command.

 

2) db. orders. remove ({"onumber": "001"}) delete data based on conditions

 

(2) Delete A set

Syntax:

Db. collection. drop () sets and indexes do not exist.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.