我需要以这样的方式查询mongodb数据库,以便field1
和field2
获得某种数据层次结构分组。实际上从shell我可以运行以下内容:
db.collection.aggregate([{'$group': {'count': {'$sum': 1}, '_id': {'field1': '$field1', 'field2': '$field2'}}}])
有没有人对java做过同样的事情?
答案 0 :(得分:1)
如果您提供示例文档会更好。
您可以将查询转换为Mongo-Java
驱动程序,如下所示:
DBCollection collection = db.getCollection("collectionName");
DBObject groupFieldsInId = new BasicDBObject();
groupFieldsInId.put( "field1", "$field1");
groupFieldsInId.put( "field2", "$field2");
DBObject groupFields = new BasicDBObject( "_id", groupFieldsInId);
groupFields.put("count", new BasicDBObject( "$sum", 1));
DBObject group = new BasicDBObject("$group", groupFields );
AggregationOutput output = collection.aggregate(group);