Learning Node.js MongoDB
- Part 1: Terminology and Comparison with SQL
- Part 2: Connecting and Creating
- Part 3: Reading
- Part 4: Updating
- Part 5: Deleting
MongoDB is a popular NoSQL document-oriented database system. The Node.js driver allows for connecting to an existing MongoDB installation or system.
Updating
Like with creating and reading, updating also follows the same “one” and “many” function pattern.
updateOne()
The function updateOne() works on an existing collection.
In MongoDB, updating looks like reading and inserting in one action. In order to update a document, it must first be found. The updateOne() function takes as the first two arguments a query to find a single document and what key-value pairs should be changed as a result.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("example");
var myquery = { name: "Dan Cox" };
var newvalues = { $set: {blogPost: "4" } };
dbo.collection("users").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
db.close();
});
});
In order to change a value, the special value $set must be used. This signals that the key-value pairs included should be updated to their new values.
updateMany()
The function updateMany() works on an existing collection.
Like with updateOne(), documents must first be found in order to be updated. Unlike the more common usage with updateOne() to find a single document, the query for multiple documents can use regular expressions to search across documents.
For example, to find all documents with a field containing the letter “a”, it would look like the following: “{ name: /a/ }”.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("example");
var myquery = { name: /a/ };
var newvalues = { $set: {blogPost: "4" } };
dbo.collection("users").updateMany(myquery, newvalues, function(err, res) {
if (err) throw err;
db.close();
});
});