【发布时间】: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