nishi
nishi

Reputation: 1265

search query on array elements in mongodb

I am new to mongodb and still learning it so my question can be naive so please bear with it :) I have only one json object in mongodb which looks like this.

json object

{
    "URLStore": [
        {
            "description": "adf description",
            "url": "www.adf.com"
        },
        {
            "description": "pqr description",
            "url": "www.pqr.com"
        },
        {
            "description": "adf description",
            "url": "www.adf.com"
        }
    ]
}

I need to query description for url which matches given input. e.g here www.adf.com . I have a code which queries mongodb

mongodb query

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("URLStore.url","www.pqr.com");
BasicDBObject fields=new BasicDBObject("URLStore.description", "");
cursor = collection.find(whereQuery,fields);

but the result is something like

{
    "_id": {
        "$oid": "554b4046e4b072dd9deaf277"
    },
    "URLStore": [
        {
            "description": "pqr description"
        },
        {
            "description": "adf description"
        },
        {
            "description": "adf description"
        }
    ]
}

Actually only 1 description should have returned as matching objects with key www.pqr.com is only one. What is wrong with my query? m I missing something here ?

I have already tried question Retrieve only the queried element in an object array in MongoDB collection but using solution mentioned there will return only one object / first match

Upvotes: 2

Views: 153

Answers (1)

chridam
chridam

Reputation: 103365

Use the following aggregation pipeline, should give you the desired results:

db.collection.aggregate([
    {
        "$match": {
            "URLStore.url": "www.adf.com"
        }
    },
    {
        "$unwind": "$URLStore"
    },
    {
        "$match": {
            "URLStore.url": "www.adf.com"
        }
    },
    {
        "$group": {
            "_id": {
                   "url": "$URLStore.url",
                   "description": "$URLStore.description"
            }
        }
    },
    {
        "$project": {
            "_id": 0,
            "description": "$_id.description"
        }            
    }
])

Upvotes: 3

Related Questions