有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有正则表达式过滤器的MongoDB Java驱动程序聚合

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

假设我有json:

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

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

预期结果是:

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

共 (3) 个答案

  1. # 1 楼答案

    你可以使用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);
    
  2. # 2 楼答案

    就Mongo Shell命令而言,felix提供的answer是正确的。使用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 }  
    
  3. # 3 楼答案

    您可以通过在$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