请帮助我使用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"} } }
)
答案 0 :(得分: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();
答案 1 :(得分: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 results = mongoQuery.execute(mongoDB); 在我看来,整合和使用非常快。
另外还有另一个很棒的图书馆:
使用此功能,您可以使用以下代码:
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);