I have a java code that retrieves a bson.Document from MongoDB. An example JSON/BSON document is:
{
"field1": "text1",
"field2": {
"field2Sub1": "text2"
}
}
In my java code I manipulate it like this to get values of field1
and field2Sub1
com.fasterxml.jackson.databind.ObjectMapper objectMapper;
org.bson.Document documentFromMongo = this.getDocumentFromMongo();
org.bson.Document field2Document = documentFromMongo.get("field2", Document.class);
String field1Value = objectMapper.convertValue(documentFromMongo.get("field1"), String.class);
String field2Sub1Value = objectMapper.convertValue(field2Document.get("field2Sub1"), String.class);
Is there any way or some library or method I can use to get the value of field2Sub1 like this way:
String field1Value = objectMapper.convertValue(documentFromMongo.get("field2.field2Sub1"), String.class);
I don't know of another library doing this, but you could use
org.bson.Document
provided functionality to achieve similar effect. It's quite simpleDocument.getEmbedded()
Like so:
The
extractValue
method does the trick - first split by dot and build a list, becausegetEmbedded
accepts a list, thengetEmbedded
handles the rest.