I have a nested MongoDB document as shown below:
{
"product_id": "123",
"properties": {
"Category": {
"type": "object",
"Electronics": {
"type": "object",
"Mobile": {
"type": "string"
},
"Laptop": {
"type": "string"
}
},
"Clothing":{
"type":"object",
"Men":{
"type":"string"
},
"women":{
"type":"string"
}
}
},
"_id": {
"type": "string"
},
"internal":{
"type":"object",
"hsn":{
"type":"string"
},
"asr":{
"type":"int"
}
}
}
}
We have a collection of such documents where the product_id is unique. For a give product_id we have to return the type of a given property.
For example: Return the type of category.electronics.mobile
for product_id : 123. In this case output will be returned as "String". There can be any number of properties and can have any nested level.
I am trying to use this code to fetch the result:
FindIterable<Document> hierarchialResults = database.getCollection("test").find(Filters.and(
eq("product_id", "123")
)).projection(fields(include("category.electronics.mobile.type")));
But the above code gives me a document with key properties and when I do a get("properties") then it again returns a document with key "category" and when I get("category") then it returns a document with key ("Electronics") and it continues. I just want the type of my nested property passed and don't want to iterate again and again.
How to do this? Please share example in context with mongodb-java-driver.