【问题标题】:MongoDB Java Driver aggregation with regex filter带有正则表达式过滤器的 MongoDB Java 驱动程序聚合
【发布时间】:2018-03-26 07:34:08
【问题描述】:

我正在使用 MongoDB Java 驱动程序 3.6.3。 我想通过聚合创建正则表达式查询以检索不同的值。

假设我有 json:

[{
  "name": "John Snow",
  "category": 1
},
{
  "name": "Jason Statham",
  "category": 2
},
{
  "name": "John Lennon",
  "category": 2
},
{
  "name": "John Snow",
  "category": 3
}]

我想创建正则表达式类似于“John.*”的查询,并按名称对其进行分组,这样就只有一个“John Snow”

预期结果是:

[{
  "name": "John Snow",
  "category": 1
},
{
  "name": "John Lennon",
  "category": 2
}]

【问题讨论】:

    标签: java mongodb aggregation-framework mongodb-java


    【解决方案1】:

    felix 提供的answer 是正确的,就 Mongo Shell 命令而言。该命令使用 MongoDB Java 驱动程序的等效表达式为:

    MongoClient mongoClient = ...;
    
    MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");
    
    AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
    
        // Java equivalent of the $match stage
        Aggregates.match(Filters.regex("name", "John")),
    
        // Java equivalent of the $group stage
        Aggregates.group("$name", Accumulators.first("category", "$category"))
    
    ));
    
    for (Document document : documents) {
        System.out.println(document.toJson());
    }
    

    上面的代码会打印出来:

    { "_id" : "John Lennon", "category" : 2 }  
    { "_id" : "John Snow", "category" : 1 }  
    

    【讨论】:

      【解决方案2】:

      您可以在 $match 阶段使用$regex 来实现此目的,然后是 $group 阶段:

      db.collection.aggregate([{
          "$match": {
              "name": {
                  "$regex": "john",
                  "$options": "i"
              }
          }
      }, {
          "$group": {
              "_id": "$name",
              "category": {
                  "$first": "$category"
              }
          }
      }])
      

      输出:

      [
        {
          "_id": "John Lennon",
          "category": 2
        },
        {
          "_id": "John Snow",
          "category": 1
        }
      ]
      

      你可以在这里试试:mongoplayground.net/p/evw6DP_574r

      【讨论】:

      【解决方案3】:

      您可以使用Spring Data Mongo

      喜欢这个

          Aggregation agg = Aggregation.newAggregation(
              ggregation.match(ctr.orOperator(Criteria.where("name").regex("john", "i")),
                      Aggregation.group("name", "category")
              );
                AggregationResults<CatalogNoArray> aggResults = mongoTemp.aggregate(agg, "demo",demo.class);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-15
        • 2016-02-11
        • 2014-11-06
        • 1970-01-01
        • 2016-08-03
        • 2012-04-22
        • 2014-08-11
        相关资源
        最近更新 更多