updating and deleting data in the MongoDB database

Source: Internet
Author: User
Tags mongodb

updating and deleting data in the MongoDB database

In the MongoDB database, you can use the Update method of the collection object to update the data document in the collection. Use the following method:

Collection.update (selector, document, [options], [callback]);

Selector parameter : The parameter value is an object that is used to query the data document that needs to be updated. The parameter value specifies exactly the same method as the selector parameter value used in the Find method that we used earlier.

Document parameter : The parameter value is an object that specifies the data document to update.

Options parameter: This parameter value is an object that specifies the option to use when updating data, and several common options properties are described below:
1. Upsert The property value is a Boolean value that specifies whether the Upsert operation is performed when the new data is being used, and the so-called Upsert operation refers to inserting a piece of data when the updated data document does not exist
The operation of the document. The property value defaults to False.

2. Multi: This property value is also a Boolean value that specifies whether to update all data documents that meet the query criteria. The default value is False (only the first data document that meets the query criteria is updated).

callback parameter : Used to specify the callback function to execute at the end of execution of the update data operation, the specified method of the callback function is as follows:

function (Err, result) {};

The Err parameter is the error object that is thrown when the update data operation fails, the result parameter value is an integer value that represents the number of data bars that were successfully updated, and the property value is null when the update data operation fails.

First of all, let's start by looking at all the data in the Users collection in the database as follows, using the following code:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.find ({}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{console.log (docs);          Db.close ();      }        });  }    }); }});

As shown in the following:

And now we use the Update method to update the above data, I would like to update the username= ' empty intelligence ' data into ' lone 0707 ', using the following methods:

Collection.update ({}, {userName: ' lone 0707 '});

All the following code:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.update ({}, {userName: ' Lone 0707 '},function(err, result) {if(err) {Throwerr; } Else{collection.find ({}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{Console.log (' Updated data: ');                Console.log (Docs);              Db.close ();          }            });  }        })      }    }); }});

The execution run results are as follows:

As you can see, only the first data is updated, because the properties in the Options object multi default to False, and if you need to change all of the data, you need to specify the multi property in the options to true. You need to use the $set atom operator in the document parameter value object.

Change the code as follows:

true function (Err, result) {});

All the following code:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Users ',function(Err, collection) {if(err) {Throwerr; } Else {        //Start Query Collection usersCollection.update ({}, {$set: {userName: ' Lone 0707 '}}, {multi:true},function(err, result) {if(err) {Throwerr; } Else{collection.find ({}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{Console.log (' Updated data: ');                Console.log (Docs);              Db.close ();          }            });  }        })      }    }); }});

The results of the operation are as follows:

3. Understanding the Upsert property in the Options object
If you specify true for the Upsert property value in the options parameter value object, the document parameter value object is inserted into the collection when the data document that matches the query criteria does not exist in the collection.
Now let's take a look at updating a data document with an username field of ' AAA ' in the Update method, which does not exist in the Users collection, and will assign the Update method
The document parameter value object is inserted into the Users collection. The following code:

true function (Err, result) {});

The execution results are as follows:

You can see in the window that the users collection is inserted with a data AAA;

4. Remove () method deletes a data document from the collection
The method is to delete the data document in the collection, which is used as follows:

Collection.remove ([selector], [options], [callback]);

The selector parameter is used to query the data document that needs to be deleted.
The options parameter value is an object that specifies the option to use when deleting data. The common options property values are as follows:
Single: The property value is a Boolean value that specifies whether to delete only the first data document that satisfies the query criteria, and the default property value is False.

The callback parameter specifies the callback function that is executed at the end of the update data operation, and the method specified by the callback function is as follows:

function (Err, result) {}

The Err parameter is the error object that is thrown when the delete data operation fails. The result parameter value is an integer value that represents the number of data bars that were successfully deleted and NULL if the data deletion failed.

The following demo, the preferred to goods this collection after inserting data, and then before the deletion of the query under the data how many, after the query is complete, continue to delete operations, delete condition is all price
Removed for 11, as shown in all code below:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true });varDocs =[{type:' Food ', price:11}, {type:' Food ', price:10}, {type:' Food ', price:9}, {type:' Food ', price:8}, {type:' Food ', price:7},];d B.open (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection '); Db.collection (' Goods ',function(Err, collection) {Collection.insert (docs,function(Err, docs) {if(err) {Throwerr; } Else{collection.find ({}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{Console.log (The data in the goods collection before deletion is as follows: ');            Console.log (Docs);        }          });      }      }); Collection.remove ({price:11},function(err, result) {if(err) {Throwerr; } Else{collection.find ({}). ToArray (function(Err, docs) {if(err) {Throwerr; } Else{Console.log (' The data after deletion is: ');              Console.log (Docs);            Db.close ();        }          });    }      });  }); }});

As shown in the following:

Because the single property value in the Options parameter object defaults to False, all data documents that meet the query criteria are deleted, and if the property value is set to True, only the first data document that satisfies the criteria is deleted. The following code:

true function (Err, result) {});

As shown

5. Findandremove method to query and delete a data document
You can use this method to query and delete a data document, which is used in the following way:

Collection.findandremove (selector, sort, [options], callback);

The selector parameter value is an object that is used to query the data document that needs to be deleted;
The sort parameter value is an array that specifies how the data is sorted when there are multiple data documents that match the criteria of the query. The array contains two elements, each of which is an array,
The first element value is the field name used for sorting, the second element value can be 1 or -1,1 is ascending, and 1 is descending.
The options value is an object that specifies the option properties to use when deleting data.
The callback parameter specifies the callback function that ends execution when the data operation is deleted, and the callback function specifies the method as follows:

function (Err, Doc) {}

The Err parameter value is the error object that is thrown when the delete data operation fails.
The doc parameter value is an object that represents the deleted data document, which is null when the delete data fails.

updating and deleting data in the MongoDB database

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.