将 mongodb 的聚合查询转换为 spring 启动

Convert the aggregation query of mongodb for spring boot

我有一个 mongodb 查询很好用

db.user.aggregate([
  {
    "$project": {
      "data": {
        "$objectToArray": "$$ROOT"
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    "$match": {
      "data.v": {
        $regex: "Mohit Chandani"
      }
    }
  }
])

基本上,获取所有具有 Mohit Chandani 值的文档,这是输出:

{ "_id" : "b387d728-1feb-45b6-bdec-dafdf22685e2", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
{ "_id" : "8e35c497-4296-4ad9-8af6-9187dc0344f7", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
{ "_id" : "c38b6767-6665-46b8-bd29-645c41d03850", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }

我需要为我的 spring 引导应用程序转换此查询,我正在编写以下内容:-

Aggregation aggregation = Aggregation.newAggregation(Aggregation.project(Aggregation.ROOT), Aggregation.match(Criteria.where(connectionRequest.getWord())));

了解在 Spring-Data 中进行长聚合时采用哪种方法会很有帮助。

这可能对您有所帮助,希望您正在使用 MongoTemplate 进行聚合。

@Autowired
private MongoTemplate mongoTemplate;

上面脚本的代码是

public List<Object> test() {

    Aggregation.newAggregation(
        project().and(ObjectOperators.valueOf(ROOT).toArray()).as("data"),
        unwind("data"),
        match(Criteria.where("data.v").regex("Mohit Chandani")
        )
    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();

}

我不确定上面代码的 project() 是否有效,因为我还没有尝试过。我从 Spring data mongodb

中引用了它

如果不行,这个肯定行。很少有 spring 数据不支持运算,例如 $addFields$filter.. 所以我们做一个 Trick to convert

public List<Object> test() {

    Aggregation aggregation = Aggregation.newAggregation(
        
        p-> new Document("$project",
                new Document("data",
                    new Document("$objectToArray","$$ROOT")
                )     
            ),
        unwind("data"),
        match(Criteria.where("data.v").regex("Mohit Chandani"))     

    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();

}