【问题标题】:mongodb aggregate function implementation in java driverjava驱动中的mongodb聚合函数实现
【发布时间】:2017-03-29 05:49:53
【问题描述】:

如何在java中实现这个聚合查询我不知道该怎么做?

db.History.aggregate([ 
    { "$match" : {"thId":"001"}},
    { "$group" : { 
              "_id" : {"Id":"$Id","controller" : "$controller","mod" : "$mod","variable" : "$variable"}  
              ,"variable" : {"$first": "$$ROOT"}
              ,"data" : {"$push":{"value":"$value","updatedDateTime":"$updatedTime"}}
            }
    }
    ])

【问题讨论】:

  • 你能展示一下你尝试过的东西吗,

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

参考 Mongo Java 驱动Documentation

        MongoClient mongoClient = new MongoClient("localhost",27017);
        MongoDatabase database = mongoClient.getDatabase("Test");
        MongoCollection<Document> collection = database.getCollection("History");
        Document doc = new Document();
        doc.append("$match",new Document("thId","001"));
        Document group = new Document();

        group.append("$group", new Document("_id",new Document().append("Id", "$Id").append("controller", "$controller").append("mod" , "$mod").append("variable" , "$variable"))
        .append("variable" , new Document("$first", "$$ROOT"))
        .append("data",new Document().append("$push", new Document().append("value", "$value").append("updatedDateTime","$updatedTime"))));
        ArrayList<Document> docList = new ArrayList<Document>();
        docList.add(doc);
        docList.add(group);

        List<Document> results =collection.aggregate(docList).into(new ArrayList<Document>());
        for(Document res: results){
            System.out.println(res.toJson());
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多