Anshul
Anshul

Reputation: 425

Access query fields in mongodb inside forEach

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.

Upvotes: 0

Views: 1755

Answers (1)

ngShravil.py
ngShravil.py

Reputation: 5048

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

Upvotes: 3

Related Questions