How to use forEach Loop in mongoDB to manipulate document

Connect with

mongodb-logo

Well, I’m going to try to explain about forEach loop which is very powerful for housekeeping sort of job in day-to-day activities. Using of forEach loop in mongoDB is straight forward, if you know the javascript. By using for forEach loop you can manipulate documents on your collection.

You can use forEach loop in day-to-day activities as:

  1. for updating your matching/conditional document using forEach loop,
  2. for deleting your matching/conditional document using forEach loop,
  3. for manipulating value of document on matching/conditional using forEach loop

Be careful while updating anything specially on production environment. I have been using MongoDB for over 5 years and most of the time we use forEach loop which is similar to JavaScript.

Let us add some document in mycoll collection of any db in mongoDB, for this use following script to add 4 documents.

Add documents in Collection


db.mycoll.insert({"name":"ranjeet", "age":34});
db.mycoll.insert({"name":"rakesh", "age":56});
db.mycoll.insert({"name":"anushka", "age":54});
db.mycoll.insert({"name":"joe", "age":45, "dob" : new Date()});

Get all document/data from mycoll collection

db.mycoll.find({})

Output:

/* 1 */
{
    "_id" : ObjectId("57d29b1375cac9e9f04bd7c1"),
    "name" : "ranjeet",
    "age" : 34
}

/* 2 */
{
    "_id" : ObjectId("57d29b1c75cac9e9f04bd7c2"),
    "name" : "rakesh",
    "age" : 56
}

/* 3 */
{
    "_id" : ObjectId("57d29b1f75cac9e9f04bd7c3"),
    "name" : "anushka",
    "age" : 54
}

/* 4 */
{
    "_id" : ObjectId("57d29b2275cac9e9f04bd7c4"),
    "name" : "joe",
    "age" : 45,
    "dob" : ISODate("2016-09-09T11:21:06.234Z")
}

Basic of forEach

db.collection.find().forEach()
or 
var cursor = db.collection.find();
cursor.forEach(function)

Iterates the cursor to apply a JavaScript function to each document from the cursor.

The forEach() method has the following prototype form:
Parameter: function
Type: JavaScript
Description: A JavaScript function to apply to each document from the cursor. The signature includes a single argument that is passed the current document to process.

Get documents with conditional query

Get matching document(s), for (age=54 or age=56) and name=”rakesh”

Query :

db.mycoll.find({"age":{$in: [54,56]}, name: "rakesh"})

Add field in document Using forEach loop

Add field “sal” in document Using Query criteria , using forEach loop

Query :

db.mycoll.find({"age":{$in: [54,56]}, name: "rakesh"}).forEach(function(doc){
    db.mycoll.update({_id: doc._id},{$set:{"sal": 25000}});
})

Update a field using forEach loop

Update “sal” with 10 % (percent) of increment using forEach function with conditional query

Note: Before executing following script , “sal”: 25000 .

Query :


db.mycoll.find({"age":{$in: [54,56]}, name: "rakesh"}).forEach(function(doc){
  
    var updatedSal = doc.sal + (doc.sal * 10/100);
    db.mycoll.update({_id: doc._id},{$set:{"sal": updatedSal}});
	
})

Check whether you above script worked or not.

db.mycoll.find({"age":{$in: [54,56]}, name: "rakesh"})

Output:

 
{
    "_id" : ObjectId("57d29b1c75cac9e9f04bd7c2"),
    "name" : "rakesh",
    "age" : 56,
    "sal" : 27500
}

How to Delete document Using forEach

Here, I’m deleting document which match my query criteria.

db.mycoll.find({"age":{$in: [54, 56]}, name: "rakesh"}).forEach(function(doc){
    
    db.mycoll.remove({_id: doc._id});
})

Finally : Get All Documents

Query :

db.mycoll.find({})

Output:

/* 1 */
{
    "_id" : ObjectId("57d29b1375cac9e9f04bd7c1"),
    "name" : "ranjeet",
    "age" : 34
}

/* 2 */
{
    "_id" : ObjectId("57d29b1f75cac9e9f04bd7c3"),
    "name" : "anushka",
    "age" : 54
}

/* 3 */
{
    "_id" : ObjectId("57d29b2275cac9e9f04bd7c4"),
    "name" : "joe",
    "age" : 45,
    "dob" : ISODate("2016-09-09T11:21:06.234Z")
}

Reference

MongoDB doc

Write you suggestion or comment to improve this post. cheers 🙂


Connect with

1 thought on “How to use forEach Loop in mongoDB to manipulate document

  1. Right now it appears like Expression Engine is the top blogging platform available right now.
    (from what I’ve read) Is that what you are using on your blog?

Leave a Reply

Your email address will not be published. Required fields are marked *