3

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**" where location is "Houston". In case of simple JSON object I have to just pass it as query like:

BasicDBObject place = new BasicDBObject();
place.put("location", "Houston");

But in case of nested JSON I don't know how to pass it as a query and get the appropriate category. ie If I pass my location as"Houston" then it should return it's appropriate category "cat1"...i hope my question is clear now....

1 Answer 1

7

Ok, you have your documents:

db.coll1.insert({
    "myobj" : {
        "objList" : [
            { "location" : "Texas" },
            { "location" : "Houston"},
            { "name":"Sam" }
        ]
    }, 
    "category" : "cat1"
})

and

db.coll1.insert({
    "myobj" : {
        "objList" : [
            { "location" : "Tennesy" },
            { "location" : "Houston"},
            { "location" : "SF" }
        ]
    }, 
    "category" : "cat1"
})

Now you can find what you want using the dot operator:

db.coll1.find({"myobj.objList.location": "Texas"}).pretty() will return one object which has Texas

db.coll1.find({"myobj.objList.location": "SF"}).pretty() will return one object which has SF

db.coll1.find({"myobj.objList.location": "Houston"}).pretty() will return both objects

And now I hope you will be able to write it in Java. I have never used Java, but based on this question you can do something like this. If it will not work, just look how to use dot operator in java driver for mongo:

DBCursor cursor = coll1.find(new BasicDBObject("myobj.objList.location", "Texas"));

P.S. you told, that you wanted to retrieve category. In such a way, you will need to use a projection db.coll1.find({<the query I provided}, {category: 1, _id: 0})

Sign up to request clarification or add additional context in comments.

1 Comment

yeah it works fine @Salvador...+1 for your helping hand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.