How to insert Embedded Document with dotted field in MongoDb

298 Views Asked by At

Let say I have following Java org.bson.Document

Document innerDoc = new Document();
innerDoc.put("field.with.dot", "something");
Document doc = new Document("inner", innerDoc);

When I insert doc into I got "The dotted field 'field.with.dot' is not valid for storage", I checked the documentation that mongoDB doesn't allow dotted fields in nested Document.

  1. how to I get around with this? because the Document is generated dynamically, so It may have dotted fields in several levels deep. Noted: I don't want to replace the "dot" symbol.

  2. Is it possible to break down the dotted field into nested fields?

    {"inner": { 
        "field": { 
            "with": {
                 "dot": "something"
             }
         }
      }
    }
1

There are 1 best solutions below

0
On

You have to build nested documents

Document innerWithDoc = new Document();
innerWithDoc.put("dot", "something");
Document innerFieldDoc = new Document();
innerFieldDoc.put("with", innerWithDoc);
Document innerDoc = new Document();
innerDoc.put("field", innerFieldDoc);
Document doc = new Document("inner", innerDoc);

Or you can do the same in a single instruction :

Document doc = new Document("inner", 
  new Document("field", 
    new Document("with", 
      new Document("dot", "something")
    )
  )
);