Access query fields in mongodb inside forEach

1.5k Views Asked by At

In mongodb, we can use forEach() on find() method for iterating over documents inside the collection . Now the question is can we access the query field inside the forEach . For eg:-

db.mycollection.find({name : 'Mike'}).forEach(function(document) {
    // var firstName = name;
})

Can we do something like this or what alternative we can use ? Please help.

1

There are 1 best solutions below

0
ngShravil.py On BEST ANSWER

You are almost there, try the below code:

db.mycollection.find({name : 'Mike'}).forEach(function(document) {
    var firstName = document.name; // Just use the . operator
    print(firsName)
    // Rest of your operations.
})