首页 > 解决方案 > 将mongodb的聚合查询转换为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 Boot 应用程序转换此查询,并且我正在编写以下内容:-

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

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

标签: javaspringmongodbspring-dataspring-data-mongodb

解决方案


这可能会对您有所帮助,希望您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 数据 mongodb中引用它

如果它不起作用,这肯定会起作用。Spring 数据中不支持很少的操作,例如$addFields$filter.. 所以我们做了一个技巧来转换

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();

}

推荐阅读