'How to parse a bson.Document
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);
Solution 1:[1]
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 simple
- Split your input/path by dot
- Use
Document.getEmbedded()
Like so:
public class MongoMain {
private static final String JSON = "{\n" +
" \"field1\": \"text1\",\n" +
" \"field2\": {\n" +
" \"field2Sub1\": \"text2\"\n" +
" }\n" +
"}";
public static void main(String[] args) {
Document document = Document.parse(JSON);
String path = "field2.field2Sub1";
String value = extractValue(document, path);
System.out.println("extracted value - " + value);
}
private static String extractValue(Document document, String dotNotationPath) {
List<String> path = Arrays.asList(dotNotationPath.split("\\."));
return document.getEmbedded(path, String.class);
}
}
The extractValue method does the trick - first split by dot and build a list, because getEmbedded accepts a list, then getEmbedded handles the rest.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chaosfire |
