[英]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. 在mongo shell中,我正在尝试检查推送到变量中的JSON是否具有字段名称,但是由于缺少某些内容而出现错误。
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
. 在上面的代码中,我试图检查在变量p
推送的JSON文档中是否存在reR
字段。
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);
You're mixing two different things. 您正在混合两种不同的东西。 $exists has to be used inside a mongoDB query. $ exists必须在mongoDB查询中使用。 What you need here is the javascript method obj.hasOwnProperty() . 您需要的是javascript方法obj.hasOwnProperty() 。 Use it like this: 像这样使用它:
var p= db.monit.findOne({_id: 0})
if ( p.pay[0].hasOwnProperty("reR")){
print(p.pay[0].reR);
}
Use the $exists
operator within the query as: 在查询中使用$exists
运算符为:
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 ). 这将寻找一个满足上述查询条件的文档,其中_id的值为0 AND
$exists
一个具有reR
属性的嵌入式文档作为pay
数组的第一个元素(使用点符号 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.