我使用的是MongoDB Java Driver 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
}]
答案 0 :(得分:3)
根据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 }
答案 1 :(得分:1)
您可以使用 $regex
阶段中的$match
,然后是 $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
答案 2 :(得分:0)
您可以使用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);