MongoDB Java,查询数组中的元素并返回选中的值,

时间:2015-06-09 11:12:05

标签: mongodb

我在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"
    }
    }]
}

我想写一个Mongo查询来获取Java中的eventValue,其中action等于updated且name为AsiaEuropeEvents(数组)中可能有多个元素,其行为等于更新。

如何编写查询以及如何在Java中获取EventValue

提前谢谢!

1 个答案:

答案 0 :(得分:1)

我没有使用mongo 2.4(使用mongo 3.0测试)对其进行测试,但您可以使用以下内容:

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

等效的java代码是:

    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);

这将为您提供预期的输出。