【问题标题】:How to perform aggregation with MongoDB 3.0 java driver如何使用 MongoDB 3.0 java 驱动程序执行聚合
【发布时间】:2015-12-28 10:46:44
【问题描述】:

我正在尝试使用 MongoDB java 驱动程序 (3.0) 执行简单的聚合操作。需要有关如何使用 JAVA API 编写以下 mongo shell 查询的帮助。

db.coll.aggregate([
    { $project: {
        email_id: { $ifNull: [ "$email_id", " " ] },
        phone_num: { $ifNull: [ "$phone_num","NA" ] },
        id : 1,
        firstname :1,
        lastname :1,
        status : 1
        }
    },
    { $match: { status: "true"} },
    { "$group": {
        "_id": "$id",
        "details": { "$push": {
            "$concat": [ "$firstname", " ", "$lastname", " | ", "$email_id" , " | ", "$phone_num" ]
        }}
    }}
])

【问题讨论】:

  • 请在此处发布您尝试过的内容

标签: java mongodb


【解决方案1】:

这里是您的 shell 查询的 java 驱动程序查询

MongoClient mongo = new MongoClient();    
MongoDatabase database = mongo.getDatabase("your_database");
        Document emailIdDoc = new Document("$ifNull",Arrays.asList("$email_id", " "));
        Document phoneNumDoc = new Document("$ifNull", Arrays.asList("$phone_num", "NA")); 
        Document projectDoc = new Document("$project" , new Document("email_id", emailIdDoc).append("phone_num", phoneNumDoc).append("id" , 1).append("firstname" , 1).append("lastname", 1).append("status", 1));
        Document matchDoc = new Document("$match", new BasicDBObject("status", "true"));
        Document groupDoc = new Document("$group", new Document("_id", "$id").append("details", new Document("$push", concat)));
        AggregateIterable<Document> aggregationResult = db.getCollection("your_collection").aggregate(asList(projectDoc, matchDoc, groupDoc));

使用不推荐使用的方法

MongoClient mongo = new MongoClient();
    DB db = mongo.getDB("your_database");
    BasicDBObject emailId = new BasicDBObject("$ifNull",Arrays.asList("$email_id", " "));
    BasicDBObject phoneNum = new BasicDBObject("$ifNull", Arrays.asList("$phone_num", "NA"));
    DBObject project = new BasicDBObject("$project" , new BasicDBObject("email_id", emailId).append("phone_num", phoneNum).append("id" , 1).append("firstname" , 1).append("lastname", 1).append("status", 1));
    DBObject match = new BasicDBObject("$match", new BasicDBObject("status", "true")); 
    DBObject concat = new BasicDBObject("$concat", Arrays.asList( "$firstname", " ", "$lastname", " | ", "$email_id" , " | ", "$phone_num"));
    Document concatDoc = new Document("$concat", Arrays.asList( "$firstname", " ", "$lastname", " | ", "$email_id" , " | ", "$phone_num"));
    DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$id").append("details", new BasicDBObject("$push", concat)));

    AggregationOutput iterable = db.getCollection("your_collection").aggregate(project, match, group);

【讨论】:

  • 感谢您的解决方案。我们使用的是 Document 而不是“Arrays.asList”。如果您有任何包含有关 API 的适当文档的链接,请分享
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多