使用Java的MongoDB - GroupBy更多一列

时间:2017-03-10 19:34:30

标签: java mongodb

我正在尝试使用java传输PostgreSQL for MongoDB。

我有SQL

SELECT id_buyer, buyer, SUM(qtde)
FROM test.log
GROUP BY id_buyer, buyer

和我的新代码

MongoClient mongoClient = new MongoClient();

        MongoDatabase db = mongoClient.getDatabase("teste");

        MongoCollection<Document> coll = db.getCollection("log");

        DBObject groupFields = new BasicDBObject();
        groupFields.put("id_buyer", "$id_buyer"); 
        groupFields.put("buyer", "$buyer");         

        AggregateIterable<Document> mongoCollectionList = coll.aggregate(
                Arrays.asList(
                        Aggregates.group(groupFields, Accumulators.sum("qtde", "$qtde")),
                        Aggregates.project(fields(include("comprador", "Quantidade")))
                ));

        MongoCursor<Document> mongoCursor = mongoCollectionList.iterator();

        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next().toJson());

        }

结果

{ "_id" : { "id_buyer" : 2, "buyer" : "COMPS" }, "qtde" : 16703 }

如何删除&#34; id_buyer&#34;和&#34;买家&#34;进入&#34; _id&#34; ?

韩国社交协会

2 个答案:

答案 0 :(得分:0)

你尝试这样做..

  AggregateIterable<Document> mongoCollectionList = collection.aggregate(
                    Arrays.asList(
                            Aggregates.group(groupFields, Accumulators.sum("qtde", "$qtde")),
                            Aggregates.project(Projections.fields(Projections.include("qtde"),Projections.excludeId()))
                    ));

答案 1 :(得分:0)

我测试了Veeram发布的answer,它对我来说非常合适。

这是他的消化:

Aggregates.project(fields(excludeId(), 
    computed("id_buyer", "$_id.id_buyer"),
    computed("buyer", "$_id.buyer"), 
    include("comprador", "Quantidade")));