【问题标题】:Converting mongoshell projection to Spring MongoTemplate projection将 mongoshell 投影转换为 Spring MongoTemplate 投影
【发布时间】:2021-09-02 15:00:50
【问题描述】:

鉴于以下 mongoshell 查询 - 工作正常

[
  {
    '$match': {
      'id': '1'
    }
  }, {
    '$graphLookup': {
      'from': 'pages', 
      'startWith': '$cID', 
      'connectFromField': 'parent', 
      'connectToField': 'cID', 
      'as': 'result', 
      'depthField': 'level'
    }
  }, {
    '$unwind': {
      'path': '$result', 
      'preserveNullAndEmptyArrays': true
    }
  }, {
    '$sort': {
      'result.level': 1
    }
  }, {
    '$group': {
      '_id': '$id', 
      'result': {
        '$push': '$result'
      }
    }
  }, {
    '$project': {
      'result': {
        'id': 1, 
        'cID': 1, 
        'level': 1
      }
    }
  }
]

如何使用 Spring MongoTemplate 及其给定的 DSL 实现投影? 鉴于 github repo 提供的源代码和 AggregationTests,我可以是

project().and("result").nested(Fields.fields("id","cID","level")

它只返回一个空的结果列表。

【问题讨论】:

    标签: spring mongodb mongodb-query spring-data-mongodb


    【解决方案1】:

    我没有想出一个解决方案让它直接与MongoTemplate 一起工作。由于我已经在使用 Spring Data 提供的MongoRepository,因此创建聚合查询非常简单。

    public interface Repository extends MongoRepository<Object, String> {
      @Aggregation(pipeline = {
        "{'$match': {'cID': '?0'}}",
        "{'$graphLookup': {'from': 'pages', 'startWith': '$cID', 'connectFromField': 'cID', 'connectToField': 'parent', 'as': 'result', 'depthField': 'level'}}",
        "{'$unwind': {'path': '$result', 'preserveNullAndEmptyArrays': true}}",
        "{'$sort': {'result.level': -1}}",
        "{'$group': {'_id': '$id', 'result': {'$push': '$result'}}}",
        "{'$project': {'cID_list': '$result.cID', 'result': {'level': 1, 'cID': 1, 'id': 1}}}"
      })
      AggregationResults<Map<?, List<String>>> getChildrencIDs(final String cID);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 2018-08-06
      • 2013-03-28
      • 2019-03-05
      • 2018-06-14
      • 2013-01-15
      • 2022-01-28
      • 2012-10-30
      • 2010-09-15
      相关资源
      最近更新 更多