【问题标题】:How we can write this MongoDB query in Java?我们如何用 Java 编写这个 MongoDB 查询?
【发布时间】:2017-03-23 18:15:04
【问题描述】:
([{
    $match: {
        "Publication_Date": {
            $gte: ISODate("2003-01-01T00:00:00.0Z")
        },
    }
   }, {
    $group: {
        _id: {
            $year: "$Publication_Date"
        },
        total: {
            $sum: 1
        },
    }
}])

【问题讨论】:

  • 请考虑包含您收藏中的示例文档和您迄今为止尝试过的代码

标签: java mongodb mongodb-java


【解决方案1】:

只需将其“翻译”成 org.bson.Document 结构(类似于 map)并调用适当的操作(它不是查询,在这种情况下它是一个聚合):

Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2003-01-01");
Document group = new Document();
group.put("_id", new Document("$year", "$Publication_Date"));
group.put("total", new Document("$sum", 1));
AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
    new Document("$match", new Document("Publication_Date",
        new Document("$gte", date))),
    new Document("$group", group)
));

或使用 com.mongodb.client.model 包静态方法(不那么冗长):

AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
    Aggregates.match(Filters.gte("Publication_Date", date)),
    Aggregates.group(
        new Document("$year", "$Publication_Date"),
        Accumulators.sum("total", 1))));

【讨论】:

  • 如果我有另一个字段名为publicationId,并且我有一组publicationid 并由他们分组,我该怎么做?因为此查询适用于所有文档,我想应用一些修复文档,其中发布 ID 在集合中
猜你喜欢
  • 2021-09-10
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多