【问题标题】:Convert the aggregation query of mongodb for spring boot将mongodb的聚合查询转换为spring boot
【发布时间】:2021-01-15 12:15:03
【问题描述】:

我有一个运行良好的 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 中进行长聚合时采用哪种方法会很有帮助。

【问题讨论】:

  • 对于它的价值,您的聚合查询可能工作正常,但我高度怀疑它是否表现良好,因为多个管道仅用于字段上的正则表达式查询。此外,$unwind 管道阶段往往会稍微减慢操作速度,因为展开数组中的所有文档需要付出一些努力。
  • “为我的 Spring Boot 应用程序转换”是什么意思?
  • @deadshot 我需要通过 spring boot 应用程序而不是 mongodb shell 执行查询。
  • @chridam 是的,我明白你的意思

标签: java spring mongodb spring-data spring-data-mongodb


【解决方案1】:

这可能对您有所帮助,希望您使用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转过来了

如果它不起作用,这肯定会起作用。 $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();

}

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 2018-01-08
    • 2020-02-20
    • 2021-09-03
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多