How to use forEach Loop in mongoDB to manipulate document

Connect with

How to use forEach Loop in mongoDB to manipulate documentforEach loop in MongoDB is used for manipulation of document on mongo shell or client of mongoDB. Learn MongoDB forEach loop in this article.

1. Overview of forEach Loop in mongoDB

Well, I’m going to explain about mongoDB forEach loop which is very powerful for housekeeping sort of job in day-to-day activities in MongoDB. Using of forEach loop in mongoDB is straight forward, if you know javascript. By using forEach loop you can manipulate documents on your collection at any level and at any size of data. you can run javascript code at client side of MongoDB and server side of MongoDB both.

2. Why MongoDB forEach loop

You can ask your self, why you required mongoDB forEach loop? well, you can use forEach loop in day-to-day activities:

  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 12 years and most of the time we use mongoDB forEach loop which is similar to JavaScript forEach loop.

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

3. Add documents in Collection

Our objectives is not to add documents in collection, in-fact our object is to manipulate documents using forEach loop.

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()});

4. 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")
}

5. Basic of MongoDB forEach loop

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.

6. 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"})

7. 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}});
})

8. Update a field using forEach loop

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

Note: Before executing the 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
}

9. How to Delete document Using forEach loop

Here, I’m deleting document using mongoDB forEach loop which match my query criteria.

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

10. 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")
}

11. Reference

MongoDB doc

Thanks for visiting this post for MongoDB forEach loop for manipulate your documents. You can also visit MongoDB Tutorial Listing page for more articles on MongoDB document-oriented database.
Write your suggestion or comment to improve this post. cheers and Happy Learning 🙂


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 Comment

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