【问题标题】:mongodb $or always return false (const)mongodb $or 总是返回 false (const)
【发布时间】:2019-04-28 19:53:52
【问题描述】:

我制作了一个聚合管道来检索文档并添加一个新字段“过期”(布尔值),其值基于字段“expireAt”(日期)

在以下情况下认为过期字段为真:

  • expiredAt 缺失或为空或为空
  • 过期时间

这是我的试验:

{project:
expired: {
          $not: {
            $or: [{ expireAt: null }, { $gte: ['$expireAt', new Date()] }]
          }
        }
}

即使文档的 expireAt 值是 ,此代码也总是给我错误

通过执行解释:

{ '$project': { _id: true, expireAt: true, expired: { '$cons
    t': false } } }

查询结果:

  • 注意 expireAt 字段和对应的过期值
  • 今天是:27/11/2018

    {过期:假}, { expireAt: 2019-07-15T17:18:11.000Z, expired: false }, { expireAt: 2017-07-16T17:18:11.000Z, expired: false },

还有 {expireAt:{$exists:false}} 给出错误: MongoError:无法识别的表达式'$exists'at queryCallback

检查该字段是否存在的任何想法(无论其值为 null 与否)

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    以下代码对我有用:

    expired:{
    $and: ['$expireAt', { $lt: ['$expireAt', new Date()] }]
    }
    

    【讨论】:

      【解决方案2】:

      使用$cond操作符实现

      下面的查询可以帮助你:

      我在我的领域使用过date

      db.getCollection('chat').aggregate([
        {
          $project: {
            'date': 1,
            "expired": {
              $cond: {
                if: { $gte: ['$date', new Date()] },
                then: false,
                else: true
              }
            }
          }
        }
      ])
      

      $or

      db.getCollection('chat').aggregate(
         [
           {
             $project:
                {
                  date: 1,
                  expired: { $or: [ { $lt: [ "$date", new Date() ] }, { $eq: [ "$date", null ] } ] }
                }
           }
         ]
      )
      

      【讨论】:

      • 同样的结果,也不要删除$或
      • 如果 expireAt 缺失,更新后的查询(添加 $not 后)为 true
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2021-11-05
      • 2018-11-05
      • 2019-05-06
      • 2017-04-29
      • 2013-04-30
      相关资源
      最近更新 更多