MongoDB foreach Example - cursor.forEach() method & Traverse Usage
Introduction
This article focuses on the MongoDB forEach Example and traversal usage. MongoDB forEach function looping operators is a very common function that you should know if you deal with the database.
If you have the MongoDB application installed on Windows or Ubuntu, and you want to learn the cursor.forEach() method, follow the steps below. The method is very simple.
How to use Node.js with a cursor.forEach() in MongoDB?
The answer of this question depends on the driver you are using. I know that there is one way or another for all MongoDB drivers to implement cursor.forEach ().
Here are some examples:
node-mongodb-native
1 2 3 | collection.find(query).each(function(err, doc) { // handle }); |
Mongojs
1 2 3 | db.collection.find(query).forEach(function(err, doc) { // handle }); |
Monk
1 2 3 4 5 6 7 8 9 10 | collection.find(query, { stream: true }) .each(function(doc){ // handle doc }) .error(function(err){ // handle error }) .success(function(){ // final callback }); |
Mongoose
1 2 3 4 5 6 7 8 9 10 | collection.find(query).stream() .on('data', function(doc){ // handle doc }) .on('error', function(err){ // handle error }) .on('end', function(){ // final callback }); |
Update the document in the .forEach callback.
The only problem with updating the files in the .forEach callback is that you don’t know if all the documents have been updated.
To solve this problem, you must use some solutions to the asynchronous control process. Here are a few options:
asynchronous Commitment (when .js, bluebird)
Here is an example of using asynchronously using the queue function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | var q = async.queue(function (doc, callback) { // code for your update collection.update({ _id: doc._id }, { $set: {hi: 'there'} }, { w: 1 }, callback); }, Infinity); var cursor = collection.find(query); cursor.each(function(err, doc) { if (err) throw err; if (doc) q.push(doc); // dispatching doc to async.queue }); q.drain = function() { if (cursor.isClosed()) { console.log('all items have been processed'); db.close(); } } |
MongoDB ForEach Example of multiple tables joins operation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | //You can also call the function var param = db.sm_pm_paramconfig.find({ paramGroup: "BUSINESSUNIT" }); //Traversing the information table db.userinfo.find().forEach(function(item) { var arr = item.address.split("_"); //Get department name var deptName = ""; var num = -1; for (var i = 0; i < arr.length; i++) { if ("****" == arr[i]) { num = i; break; } } if (num >= 0) { deptName = arr[num + 1]; } else { deptName = "****"; } //Insert ID //Note: The object obtained by param must be toarray to traverse. var config = param.toArray(); for (var j = 0, len = config.length; j < len; j++) { if (deptName == config[j].paramValue) { //Insert new field db.userinfo.update({ "_id": item._id }, { $set: { "businessUnitId": config[j]._id } }); break; } } }) |
The MongoDB script mode is similar to writing the js operator, so it is also well understood. Thus, many complex operations can be implemented.
MongoDb Foreach with a Callback
1 2 3 4 5 6 | >var arr = ["ab","cd","ef"] >var show = function(value,index,ar){ print(value) } >arr.forEach(show) ab cd ef |
Additional – Browser-Side forEach Example
Let’s look at how forEach is similarly used in Javascript in the browser:
1 2 3 4 5 6 7 8 9 10 11 12 13 | //value is the current element value, index is the index of the current element in the array, ar is the array itself functionShowResults(value, index, ar) { document.write("value:" + value); document.write("index: " + index); document.write("name: " + this.name); document.write(" "); } varletters = ['ab', 'cd', 'ef']; varscope = { name: 'scope' }; // ShowResults is a callback function, the scope sets the context for the callback, so this callback function points to the scope variable, and the scope is an optional parameter. letters.forEach(ShowResults,scope); |
Mongodb uses foreach query and cursor traversal
The find method uses the cursor to return the result of the query, and the client implementation of the cursor gives you full control over the final result. Creating a cursor in a shell is very simple. First you have to put some documents into the collection.
Run the query and assign the returned result to a local variable.
1 2 3 4 | > var cursor = db.collection.find(); > while (cursor.hasNext()) { obj = cursor.next(); } |
The cursor class also implements the iterator interface, so you can use a forEach loop.
1 2 3 4 | > var cursor = db.people.find(); > cursor.forEach( function (x) { ... print(x.name); ... }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | db.Goods.find().forEach( function(item){ if(!item.goodsCode.indexOf("ABCD")){ var tempGoodId=item._id; var tempGoodCode=item.goodsCode; var temp=db.Goods.findOne({"goodsCode":{"$regex":"^"+tempGoodCode+".+"}}); if(temp){ // print(tempGoodCode+"="+item._id); var cursor=db.GoodAttr.find({"goodsId":tempGoodId}); cursor.forEach(function(a){ print(a); }) } } } ) |
MongoDB array traversal operation forEach
The seq
type in the following collection is double and you want to change it to int.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | { "_id" : ObjectId("592e94fee820cc1813f0b9a2"), "privateAttrs" : [ { "attrId" : "100", "seq" : 0 }, { "attrId" : "101", "seq" : 1 } ] } { "_id" : ObjectId("592e94fee820cc1813f0b9a3"), "privateAttrs" : [ { "attrId" : "102", "seq" : 0 } ] } |
Traversing the array through forEach:
1 2 3 4 5 6 7 8 9 10 | db.category.find().forEach( function(item) { item.privateAttrs.forEach( function(arr, index) { item.privateAttrs[index].seq = new NumberInt(item.privateAttrs[index].seq); } ); db.category.save(item); } ) |
The callback function in the forEach method has three parameters: the first parameter is the contents of the array traversed, the second parameter is the corresponding array index, and the 3rd parameter is the array itself.
Conclusion
We have showed you several examples of how to use forEach and cursors with MongoDB and we hope you can apply what you’ve learned to your application. If you’re working with MongoDB and need someone to manage your database security, backups, or performance please don’t hesitate to reach out to us at Object Rocket.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started