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

MongoDB Java Driver aggregation with regex filter

我正在使用 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
}]

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

felix 提供的 是正确的,就 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 }  

您可以使用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);