Java – retrieves values from nested JSON arrays in mongodb
My Mongo collection has entries in the following format
{
"myobj" : {
"objList" : [
{ "location" : "Texas" },{ "location" : "Houston"},{ "name":"Sam" }
]
},"category" : "cat1"
}
{
"myobj" :
{
"objList" : [
{ "location" : "Tennesy" },{ "location" : "NY"},{ "location" : "SF" }
]
},"category" : "cat2"
}
I want to extract the * * category * * located in "Houston" In the case of a simple JSON object, I must pass it as a query, such as:
BasicDBObject place = new BasicDBObject();
place.put("location","Houston");
But in the case of nested JSON, I don't know how to pass it as a query and get the appropriate category That is, if I pass my location as "Houston", it should return its corresponding category "CAT1"... I hope my problem is clear now
Solution
OK, you have your documents:
db.coll1.insert({
"myobj" : {
"objList" : [
{ "location" : "Texas" },"category" : "cat1"
})
and
db.coll1.insert({
"myobj" : {
"objList" : [
{ "location" : "Tennesy" },{ "location" : "SF" }
]
},"category" : "cat1"
})
Now you can use the dot operator to find what you want:
db. coll1. find({“myobj.objList.location”:“Texas”}). Pretty () will return an object with Texas
db. coll1. find({“myobj.objList.location”:“SF”}). Pretty () will return an object with SF
db. coll1. find({“myobj.objList.location”:“Houston”}). Pretty () will return two objects
Now I hope you can write it in Java I've never used java, but based on this question, you can do such a thing If it doesn't work, just look at how to use the dot operator for Mongo in the Java driver:
DBCursor cursor = coll1.find(new BasicDBObject("myobj.objList.location","Texas"));
PS: you said you wanted to retrieve categories In this way, you will need to use projection dB coll1. Find ({< my query}, {category: 1, _id: 0})
