Mongo 3.0.2 driver: how to escape dots(.) in strings?

1.6k views Asked by At

I want to put String "http://1.1.1.1/olala" into mongodb, but instead of

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

I get

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

Is there a standard way to insert string with special characters into mongodb using java?

The way I'm doing the upsert is

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

where methodName is url with commas. I tried to quote values, but instead got

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

And beside that, I suggest that there would be more "bad" characters later.

UPD more complex example, but don't understand how it will help

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

There are 1 answers

6
Harshil On

According to MongoDB --> You are allowed to use use any (UTF8) character in the field name which aren't special (contains ".", or starts with "$")

and field "http://1.1.1.1/olala" contains . which is special character in MongoDB and refers to a subdocument, so it reads it as,

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

Refer to issue tracker https://jira.mongodb.org/browse/SERVER-3229

This issue has been addressed as Works as Designed, so I don't think that there will be any update regarding this.

UPDATE

I have just noticed that update code in the question doesnot actually seem to achieve {data: "http://1.1.1.1/olala"} or even {name: "http://1.1.1.1/olala"}

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

This actually creates document with a {"name" : "test" } for key = "test" and then updates the document to

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

So, if this is not something you are trying to achieve , consider changing your logic.