Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if attribute exists in mongodb document in forEach function?

Tags:

mongodb

I use MongoDB 2.6.2. I need to check in forEach if field name exists on selected document.

db.testData.find(...).forEach(function(x){
// insert code here
})

How to check inside forEach function if x contains field name or not ?

like image 679
Volodymyr Levytskyi Avatar asked Feb 12 '23 16:02

Volodymyr Levytskyi


1 Answers

Mongo shell is a JavaScript shell, so most of the standard JavaScript methods are supported. You can check if the property exists as you would do on any regular object in JavaScript - by using hasOwnProperty() method:

db.testData.find({}).forEach(function(x){
    if (x.hasOwnProperty('name')) {
        // Do something
    }
})
like image 189
Christian P Avatar answered Feb 15 '23 05:02

Christian P