MongoDb无法从$ ifNull获得结果

时间:2015-12-24 00:01:41

标签: arrays mongodb null ifnull

使用以下脚本将引号更新为4字符串数组中保存的字符串中的转义字符,并且无法使$ ifnull起作用。尝试了各种形式,最新的是:

var myCursor = db.collection.Fence.find( { "properties.d.v" : { $regex : '.*".*'} } );

while (myCursor.hasNext())
{
    printjson( myCursor.next() );
    var fence = myCursor.next();
    var test;

    test = { $ifNull: [ fence.properties.d.v[0], "null" ] }
    print ( "0: ", test );
    $cond: [ { $eq: [ test, "null" ] }, fence.properties.d.v[0], fence.properties.d.v[0].replace( '"', '\"' ) ];
    test = { $ifNull: [ fence.properties.d.v[1], "null" ] }
    print ( "1: ", test );
    $cond: [ { $eq: [ test, "null" ] }, fence.properties.d.v[1], fence.properties.d.v[1].replace( '"', '\"' ) ];
    test = { $ifNull: [ "fence.properties.d.v[2]", "null" ] }
    print ( "2: ", test );
    $cond: [ { $eq: [ test, null ] }, fence.properties.d.v[2], fence.properties.d.v[2].replace( '"', '\"' ) ];
    test = { $ifNull: [ "fence.properties.d.v[3]", "null" ] }
    print ( "3: ", test );
    $cond: [ { $eq: [ test, null ] }, fence.properties.d.v[3], fence.properties.d.v[3].replace( '"', '\"' ) ];

    db.au.com.bluedot.application.model.geo.Fence.update( { _id : fence._id }, fence );
}

即使v [1]为null,测试变量仍然会从print语句输出以下内容:

1:  [object Object]

然后从replace语句返回以下错误:

2015-12-24T10:54:14.301+1100 TypeError: Cannot call method 'replace' of null

如果有更好或更简单的方法来查找和转义MongoDb中的引号,很高兴知道。

1 个答案:

答案 0 :(得分:0)

上述评论中的BatScream;你可以通过检查

来简单地替换
if(fence.properties.d.v[0]){//code to replace}

您无需为此目的使用mongoDB运算符。