【问题标题】:Convert MongoDB query into Spring MongoDB syntax将 MongoDB 查询转换为 Spring MongoDB 语法
【发布时间】:2019-03-01 19:30:37
【问题描述】:

您好,我无法将以下mongoDB查询转换为spring查询,我尝试了多种方法,但没有得到结果。

db.getCollection('FarmerCropDataLog').aggregate([
        {
            "$match" : 
            {
                "cropData.crop" : "RICE",
                 "creationTime" :
                  {
                      $lt  : 1551447981473.0
                  }
            }
        },
        {
            "$group" :
            {
                _id : null,
                "average" :{
                        $avg : "$cropData.cropPrice"
                },
                "max" :{
                        $max : "$cropData.cropPrice"
                },
                "min":{
                        $min : "$cropData.cropPrice"
                }
            }
        }
    ])

我已经编写了以下代码,但无法考虑下一步。

Query query = new Query();

query.addCriteria(Criteria.where(FarmerCropDataLog.Constants.CROP_LOG).elemMatch(Criteria.where(CropData.Constants.CROP).is(getComparisonSheet.getCrop())));

query.addCriteria(Criteria.where(FarmerCropDataLog.Constants.CREATION_TIME).gt(Year * DIFF));

【问题讨论】:

    标签: spring mongodb


    【解决方案1】:

    您有没有想过使用 MongoDB 指南针?它将使您的工作变得非常简单。

    1. 打开MongoDB compass 连接到您的实例
    2. 聚合选项卡,构建您的管道
    3. 点击save pipeline选项旁边的三个点(...)
    4. 选择export to language并选择Java
    5. 您的查询已准备就绪

    这里是java查询

    Arrays.asList(match(and(eq("cropData.crop", "RICE"), lt("creationTime", 1551447981473.0d))), group(new BsonNull(), avg("average", "$cropData.cropPrice"), max("max", "$cropData.cropPrice"), min("min", "$cropData.cropPrice")))
    

    【讨论】:

      【解决方案2】:

      如果您使用过 JpaRepository,那么很容易理解,您可以创建一个接口并扩展 MongoRepository,就像使用 JpaRepository 一样,它提供了一些简单的方法,您不需要实现它。

      你可以使用(例如考虑一个有名字和姓氏的人)

      基于 MongoDB JSON 的查询方法和字段限制

      public interface PersonRepository extends MongoRepository<Person, String>
      
      @Query(value="{ 'firstname' : ?0 }", fields="{ 'firstname' : 1, 'lastname' : 1}")
      List<Person> findByThePersonsFirstname(String firstname);
      }
      

      地理空间存储库查询

      public interface PersonRepository extends MongoRepository<Person, String>
      
        // { 'location' : { '$near' : [point.x, point.y], '$maxDistance' : distance}}
        List<Person> findByLocationNear(Point location, Distance distance);
      }
      

      Read the Spring document here for MongoDB repositories

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-09
        • 2018-01-08
        • 2020-10-14
        • 1970-01-01
        • 2018-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多