【问题标题】:MongoDb cannot get result from $ifNullMongoDb 无法从 $ifNull 获取结果
【发布时间】:2016-03-30 11:17:42
【问题描述】:

我正在使用以下脚本将引号更新为 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] 为空,测试变量仍会从 print 语句中输出以下内容:

1:  [object Object]

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

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

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

【问题讨论】:

  • 您可以通过检查 - if(fence.properties.d.v[0]){//code to replace} 来简单地 replace。为此,您无需使用 mongoDB 运算符。
  • 当然!哦。非常感谢。
  • fence.properties.d.v[n] 只检索字符串的第一个字符有什么明显的原因吗?
  • fence.properties.d.v字符串 吗?我认为它是array。如果它是一个字符串,v[n] 会给你nth 位置的字符。你可以检查 - if(fence.properties.d.v){// code to replace the first and last characters}
  • 谢谢;只是其中一个字符串是单个字符(当它应该是一致的 7 时)。

标签: arrays mongodb null ifnull


【解决方案1】:

来自上述 cmets 中的BatScream;你可以简单地通过检查来替换

if(fence.properties.d.v[0]){//code to replace}

您不需要为此使用 mongoDB 运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2021-04-24
    • 1970-01-01
    • 2020-10-26
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多