2

请帮助我使用 Java MongoDB 驱动程序将以下 MongoDB 查询转换为基于 Java 的查询。谢谢你。

db.playerscorecollection.aggregate(
      { $unwind: "$scorearray"},
      { $group: { _id: { player: "$player", venue: "$scorearray.venue", score: "$scorearray.score" } } },
      { $sort: { "_id.score" : 1 } },
      { $group: { _id: "$_id.player", maxScore: { $last: "$_id.score" }, venue: { $last: "$_id.venue"} } }
)
4

2 回答 2

4

我没有检查语法。另外我不知道您的查询是否有效,但这是我的尝试。

        //unwind
        DBObject unwind = new BasicDBObject("$unwind", "$scorearray");
        // Now the $group operation
        DBObject groupFields = new BasicDBObject("player", "$player");
        groupFields.put("venue", "$scorearray.venue"));
        groupFields.put("score", "$scorearray.score"));
        DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", groupFields));
        //sort
        DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id.score":1));
        //secondgroup
        DBObject secondGroupFields = new BasicDBObject("_id", "$_id.player")
        secondGroupFields.put("maxScore", new BasicDBObject("$last":"$_id.score"));
        secondGroupFields.put("venue", new BasicDBObject("$last":"$_id.venue"));
        DBObject secondGroup = new BasicDBObject("$group", secondGroupFields);

        // run aggregation
        AggregationOutput output = playerScoreCollection.aggregate(unwind, group,sort,secondGroup);

        Iterable<DBObject> result = output.results();
        Iterator<DBObject> iterator = result.iterator();
于 2013-07-13T09:38:09.633 回答
1

您可以使用此库: https ://github.com/EqualExperts/mongo-shell-like-query 使用此库,您可以使用查询字符串,例如:

db.users.aggregate([{'$match':{'salary': {$gte:'from#Long',$lte:'to#Long'}}}, { $group: {_id:'$role ', 'age': {$sum: '$age' } } }, { '$sort': { 'age': -1 } }, { '$limit': 5 }])

或者

db.users.aggregate({'$match':{'salary' : {$gte:'from#Long',$lte:'to#Long'}}}, { $group: {_id:'$role' , 'age': {$sum: '$age' } } }, { '$sort': { 'age': -1 } }, { '$limit': 5 })

像下面这样传递这些字符串: String query = ”db.users.find( { 'name' : 'John'} )”; MongoQueryParser 解析器 = new MongoQueryParser(); MongoQuery mongoQuery = parser.parse(query, new HashMap()); BasicDBList 结果 = mongoQuery.execute(mongoDB); 在我看来,集成和使用非常非常快。

或者,还有另一个很棒的库:

http://jongo.org

有了这个,你可以使用如下代码:

DB db = new MongoClient().getDB("dbname");
Jongo jongo = new Jongo(db);
MongoCollection friends = jongo.getCollection("friends");
friends.aggregate("{$project:{sender:1}}")
    .and("{$match:{tags:'read'}}")
    .and("{$limit:10}")
    .as(Email.class);
于 2015-09-14T18:52:29.597 回答