在旧版本的 MongoDB 中是不是有 $expr 的替代方案?

Posted

技术标签:

【中文标题】在旧版本的 MongoDB 中是不是有 $expr 的替代方案?【英文标题】:Is there an alternative for $expr in older version of MongoDB?在旧版本的 MongoDB 中是否有 $expr 的替代方案? 【发布时间】:2021-12-24 15:54:24 【问题描述】:

我编写了一个 MongoDB 查询来获取在给定日期(匹配年份和月份)关闭的订单:

const orders = await OrderModel.find(
  $expr: 
    $and: [
       $eq: ['$entityId', entityId] ,
       $ne: ['$closingDate', null] ,
       $eq: [ $year: '$closingDate' , date.getFullYear()] ,
       $eq: [ $month: '$closingDate' , date.getMonth() + 1] ,
    ],
  ,
).lean();

原来我的本地 MongoDB 版本 (3.6) 高于开发环境中的版本 (3.4.14),因此不支持 $expr。我可以使用旧版本的替代品吗?

注意:我阅读了有关此主题的 other thread,但我无法从中提取答案,因为它涵盖了不同的用例。

【问题讨论】:

你试过避开$expr吗?喜欢this example @J.F.是的,避免它是我想要做的!我只是不知道这个特定的用例 - 使用 $month 和 $year 运算符。标准的 .find() 查询是否支持它们? 嗯,没错,您正在使用$year$month。所以也许你可以使用aggregate$match 而不是find 我将查询更改为查找closingDate: $ne: null, $gte: current, $lt: next ,它似乎正在工作。谢谢! 请不要粘贴截图,使用格式化文本。见meta.***.com/q/285551/3027266 【参考方案1】:

当您必须处理日期/时间时,我推荐moment.js 库。看起来,您想查询当月的数据。然后你可以这样写:

db.OrderModel.find(
  entityId: entityId,
  closingDate: 
    $gte: moment().startOf('month').toDate(), 
    $lte: moment().endOf('month').toDate() 
  
)

你不需要closingDate: $ne: null,它是多余的。

【讨论】:

以上是关于在旧版本的 MongoDB 中是不是有 $expr 的替代方案?的主要内容,如果未能解决你的问题,请参考以下文章

mongodb $exists 在 mongodb 的 $expr 中

关于spring-boot中mongodb包的一个奇怪的版本问题

API 是不是应该在 API 响应中发回 UI 层文本/数据以允许在旧的 android/ios 应用程序版本中随时更改?

是否可以在 Angular JS 中进行服务器端渲染(在旧版本中,即 2.0 之前的版本)?

npm 卡在旧版本上,但似乎有多个版本

在旧版本中视图是纵向的