N Raghu
N Raghu

Reputation: 746

mongodb : check if the field exists in the JSON

In mongo shell I'm trying to check a JSON pushed into a variable has the field name or not.However, I'm getting error for missing something.

var p= db.monit.findOne({_id: 0})
if ("p.pay[0].reR": {$exists: true})
    print(p.pay[0].reR)

In the above code, I'm trying to check if reR field exists in the JSON document pushed in variable p.

Upvotes: 0

Views: 2676

Answers (3)

felix
felix

Reputation: 9285

You're mixing two different things. $exists has to be used inside a mongoDB query. What you need here is the javascript method obj.hasOwnProperty(). Use it like this:

 var p= db.monit.findOne({_id: 0})
 if ( p.pay[0].hasOwnProperty("reR")){
        print(p.pay[0].reR);
    }

Upvotes: 3

chridam
chridam

Reputation: 103445

Use the $exists operator within the query as:

var p = db.monit.findOne({
    "_id": 0,
    "pay.0.reR": { "$exists": true }
})
if (p !== null) printjson(p.pay[0].reR)

This will look for a document that statisfies the above query where the _id has value 0 AND there $exists an embedded document with a property reR as the first element of the pay array (using the dot notation).

Upvotes: 0

Riya Saxena
Riya Saxena

Reputation: 99

I think you should try using,

var p=db.monit.findOne({_id: 0});
var q = db.monit.findOne("p.pay[0].reR": {$exists: true});
if(q)
 print(p.pay[0].reR);

Upvotes: 1

Related Questions