Mongo 3.0.2驱动程序:如何在字符串中转义点(。)?

时间:2015-06-23 07:30:15

标签: java mongodb escaping special-characters insertion

我想把String" http://1.1.1.1/olala"进入mongodb,而不是

{data: "http://1.1.1.1/olala"}

我得到了

{data: {"http://1": {1: {1: "1/olala"}}}}

有没有一种标准的方法可以使用java?

将带有特殊字符的字符串插入到mongodb中

我做upsert的方式是

collection.updateOne(new Document("name", key), 
                     new Document("$inc", new Document(methodName, 1)), 
                     opt.upsert(true), null);

其中methodName是带逗号的网址。我试着引用值,但是得到了

{data: {"'http://1": {1: {1: "1/olala'"}}}}

除此之外,我建议会有更多"坏"人物以后。

UPD更复杂的例子,但不了解它将如何帮助

final UpdateOptions opt = new UpdateOptions();
final String methodName = "http://1.1.1.1/ololo";
final MongoCollection<Document> collection =
    MongoAsyncClientFactory.getCollection();
//final String key = Statistics.getMainKey();
final String key = "any-key-you-want";
collection.updateOne(new Document("name", key),
                     new Document("$inc", new Document(methodName, 1)),
                     opt.upsert(true), null);

1 个答案:

答案 0 :(得分:0)

根据MongoDB - &gt; 您可以在字段名称中使用任何(UTF8)字符,这些字符不是特殊的(包含&#34;。&#34;,或者以&#34; $&#34;开头)

和字段"http://1.1.1.1/olala"包含.,它是MongoDB中的特殊字符并引用子文档,因此将其读作,

 {"http://1": 
    {1: 
       {1: 
          "1/olala" : someValue
       }
    }
 }

请参阅问题跟踪器https://jira.mongodb.org/browse/SERVER-3229

此问题已解决为 Works as Designed ,因此我不认为会有任何有关此问题的更新。

<强>更新

我刚刚注意到问题中的更新代码实际上似乎无法实现{data: "http://1.1.1.1/olala"}甚至{name: "http://1.1.1.1/olala"}

collection.updateOne(new Document("name", key), 
                     new Document("$inc", new Document(methodName, 1)), 
                     opt.upsert(true), null);

这实际上为{"name" : "test" }创建了key = "test"的文档,然后将文档更新为

{
  "http://1" : {"1" : { "1" : { "1/ololo" : 1 }
    }
  },
  "name" : "test"
}

因此,如果这不是您想要实现的目标,请考虑更改您的逻辑。