簡體   English   中英

將MongoDB查詢轉換為Spring MongoDB語法

[英]Convert MongoDB query into Spring MongoDB syntax

您好,我無法將以下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));

您是否曾經考慮過使用MongoDB羅盤? 這將使您的工作非常簡單。

  1. 打開MongoDB compass連接到您的實例
  2. 聚合選項卡,構建您的管道
  3. 單擊save pipeline選項旁邊的3個點(...)
  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")))

在此處輸入圖片說明

在此處輸入圖片說明

如果您使用過JpaRepository,則很容易關聯,就可以像創建JpaRepository一樣創建一個接口並擴展MongoRepository,它提供了一些簡單的方法,並且您不需要實現它。

您可以使用(例如,考慮具有姓氏和名字的人)

基於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);
}

在此處閱讀Spring文檔以獲取MongoDB存儲庫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM