MongoDB with Java - GroupBy 多一栏 [英] MongoDB with Java - GroupBy more one column

查看:58
本文介绍了MongoDB with Java - GroupBy 多一栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 java 为 MongoDB 传输 PostgreSQL.

i am trying transfer the PostgreSQL for MongoDB using java.

我有 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 }

如何删除_id"中的id_buyer"和buyer"?

How do i remove "id_buyer" and "buyer" that is into "_id" ?

谢谢

推荐答案

我已经测试了 答案 由 Veeram 发布,它非常适合我.

I have tested the answer posted by Veeram and it worked perfectly for me.

这是他的建议:

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

这篇关于MongoDB with Java - GroupBy 多一栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆