繁体   English   中英

MongoDB 中的 Sql 查询等效项

[英]Sql Query Equivalent in MongoDB

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

我需要使用 mongoDB 而不是 MySql 更改 @Query 的主体。

谢谢你。

我可能应该添加一条评论,从 OP 请求更多信息,而不是发布答案,但本着尝试将该 SQL 语句转换为等效的 MongoDB 查询(和数据环境)的精神,此数据:

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

由这个简单的管道处理:


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

将只产生_id:0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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