简体   繁体   中英

Convert MongoDB query into Spring MongoDB syntax

Hello I am unable to convert the following mongoDB query into spring query, i have tried multiple ways, but did not get the result.

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"
                }
            }
        }
    ])

I have written follwing code, but unable to think about next step.

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

Have you ever thought about using MongoDB compass? It will make your work very simple.

  1. Open MongoDB compass connect to your instance
  2. Aggregation tab, construct your pipeline
  3. click on the 3 dots(...) next to save pipeline option
  4. Select export to language and select Java
  5. Your query is ready

Here is the java query

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")))

在此处输入图片说明

在此处输入图片说明

If you've used JpaRepository then it's easy to relate that you can create an interface and extends MongoRepository just like with JpaRepository and it provides some simple method, and you don't need the implement it.

you can use (for example consider A Person with First and Last name)

MongoDB JSON based query methods and field restriction

public interface PersonRepository extends MongoRepository<Person, String>

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

Geo-spatial repository queries

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM