简体   繁体   中英

Sql Query Equivalent in MongoDB

i have this query in Spring MySql :

@Query(value="SELECT if(Count(*) > 0, 'true', 'false') as bool FROM season c WHERE c.archived=0 and c.user_seasons_id=:idUser and :seasondate BETWEEN c.date_debut and c.date_fin",nativeQuery = true) public Boolean existsSeasonDates(@Param ("seasondate") Date seasondate,@Param ("idUser") Long idUser);

I need to change the body of @Query with mongoDB instead of MySql.

Thank you.

I should probably add a comment requesting more info from the OP instead of posting an answer but in the spirit of trying to translate that SQL statement into the equivalent MongoDB query (and data environment), this data:

var r =
[
 // IN: Only good one:                                                                                              
 { _id: 0, archived: 0, user_seasons_id: "U1",
   date_debut: new ISODate("2020-01-01"), date_fin: new ISODate("2020-01-06") }

 // OUT: seasondate is beyond date_fin                                                                          
 ,{ _id: 1, archived: 0, user_seasons_id: "U1",
   date_debut: new ISODate("2020-01-01"), date_fin: new ISODate("2020-01-03") }

 // OUT:  Right range, wrong ID.                                                                                    
 ,{ _id: 2, archived: 0, user_seasons_id: "U99",
   date_debut: new ISODate("2020-01-01"), date_fin: new ISODate("2020-01-06") }

 // OUT:  not archived == 0                                                                                         
 ,{ _id: 3, archived: 1, user_seasons_id: "U99",
    date_debut: new ISODate("2021-01-01"), date_fin: new ISODate("2021-01-03") }
         ];

processed by this simple pipeline:


seasondate = new ISODate("2020-01-04");
user = "U1";

c = db.foo.aggregate([
{$match: {
        "archived":0
        ,"user_seasons_id":user
        ,"date_debut": {"$lt": seasondate}
        ,"date_fin": {"$gte": seasondate}
    }}
]);

will yield just _id:0 .

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