user84592
user84592

Reputation: 4882

MongoDB Java, query elements in the array and return selected value,

I have following records in Mongo 2.4,

    {
    "name": "AsiaEurope",
    "events": [{
    "action": "updated",
    "someHeaderField": "field1",
    "version":"3.3",
    "eventValue": {
        "local": "newZealand",
        "remote": "India"
    }
    }, {
    "action": "new",
    "someHeaderField": "field1",
    "version":"3.3",
    "eventValue": {
        "local": "Japan",
        "remote": "England"
    }
    }, {
    "action": "finished",
    "someHeaderField": "field1",
    "version":"3.2",
    "eventValue": {
        "local": "Brasil",
        "remote": "Turkey",
        "middlebox": "Russia"
    }
    }, {
    "action": "updated",
    "someHeaderField": "field1",
    "version":"3.2",
    "eventValue": {
        "local": "Canada",
        "remote": "Cuba"
    }
    }]
}

I want to write a Mongo query to get eventValue in Java where action equals to updated and name is AsiaEurope. There could be multiple elements in the Events (array) whose action equals to updated.

How to write the query and how to fetch EventValue in Java?

Thank you in advance!

Upvotes: 0

Views: 788

Answers (1)

Vishwas
Vishwas

Reputation: 7067

I did not tested it with mongo 2.4 (tested with mongo 3.0), but you can use something like following :

db.collection.aggregate({
    "$match": {
    "name": "AsiaEurope"
    }
}, {
    "$unwind": "$events"
}, {
    "$match": {
    "events.action": "updated"
    }
}, {
    "$project": {
    "_id": 0,
    "eventValue": "$events.eventValue"
    }
}).pretty()

And equivalent java code is :

    ArrayList<BasicDBObject> pipeline = new ArrayList<BasicDBObject>();

    BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("name","AsiaEurope" ));
    BasicDBObject unwind = new BasicDBObject("$unwind", "$events");
    BasicDBObject match2 = new BasicDBObject("$match", new BasicDBObject("events.action","updated"));
    BasicDBObject project = new BasicDBObject("$project", new BasicDBObject("eventValue","$events.eventValue").append("_id",0));

    pipeline.add(match);
    pipeline.add(unwind);
    pipeline.add(match2);
    pipeline.add(project);
    AggregationOutput cursor = collection.aggregate(pipeline);

This will give you expected output.

Upvotes: 1

Related Questions