【问题标题】:MongoDb query to java code using aggregatesMongoDb 使用聚合查询 java 代码
【发布时间】:2018-08-09 07:20:59
【问题描述】:

谁能帮我把下面的查询转换成java代码?

我在 java 中编写了如下查询,但出现以下错误,

命令失败,出现错误 168:服务器上的“无法识别的表达式 '$push'”。完整的响应是 { "ok" : 0.0, "errmsg" : "Unrecognized expression '$push'", "code" : 168, "codeName" : "InvalidPipelineOperator" }

查询:

db.getCollection('xyz').aggregate([
             {$match: { "_id":{$in: [{"a" : "NA","b" : "HXYZ","c" : "12345","d" : "CA"}]}
                     }
                   },
              { $unwind: '$bal' },
              {
                 $sort: {'bal.date': -1}
              },
              {$group:
                   {"_id": "$_id",bal:{$push:'$bal'}}},
               { $project: {
            balances: { $slice: ["$bal",2]} 
                            }
               }

       ])

Java 代码:

List<Document> findDocument=collectionName.aggregate(
            Arrays.asList(
                Aggregates.match(in("_id",tempList)),
            Aggregates.unwind("$bal"),
            Aggregates.sort(Sorts.descending("bal.date")),
            Aggregates.group(new Document("_id","$_id").append("bal",new Document("$push","$bal"))),
        Aggregates.project(new Document("bal",new Document ("$slice",Arrays.asList("$bal", 2)))))).into(new ArrayList<Document>());

Mongo DB 版本是 3.4。 有人能告诉我为什么 $push 不起作用吗? 提前致谢。

【问题讨论】:

    标签: java mongodb aggregation-framework


    【解决方案1】:

    您将文档推送到 id 字段而不是单独创建推送文档。

    import static com.mongodb.client.model.Accumulators.*;
    import static com.mongodb.client.model.Aggregates.*;
    import static com.mongodb.client.model.Filters.in;
    import static com.mongodb.client.model.Sorts.*;
    import static java.util.Arrays.*;
    List<Document> results = collectionName.aggregate(
         asList(
              match(in("_id",tempList)),
              unwind("$bal"),
              sort(descending("bal.date")),
              group("$_id", push("bal","$bal")),
              project(new Document("bal",new Document ("$slice", asList("$bal", 2))))
        )
    ).into(new ArrayList<>());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多