我有一个MongoDB用户集合.用户可以随时激活和停用自己.我正在存储每次激活的开始和结束日期.现在,我想要获取在特定日期处于活动状态的用户列表.

记录是这样的:

{
  "active" : true,
  "endDates" : [
     16.11.2021,
     27.06.2020
  ],
  "startDates" : [
    21.10.2022,
    16.10.2021,
    09.04.2020
  ]   
}

在上面的示例中,startDates多于endDates,因为用户此时处于活动状态.

现在,如果我想判断用户在12.05.202022.11.2022上是否处于活动状态,它应该返回TRUE,但它应该返回17.12.2021的FALSE.

我try 在endDates和startDates上使用展开,如下所示:

collection
  .aggregate([
    { $match: {} },
    { $unwind: '$endDates' },
    { $unwind: '$startDates' },
  ])

但它给了我所有可能的开始和结束日期组合,并返回6个文档,这对查找日期范围没有用处.

推荐答案

设置数据格式的一种 Select 是使用$dateFromString将这些字符串格式化为正确的日期,使用$zip$reverseArray以正确的顺序将它们连接在一起:

db.collection.aggregate([
  {$project: {
      endDates: {
        $map: {
          input: "$endDates",
          in: {$dateFromString: {
              dateString: "$$this",
              format: "%d.%m.%Y"
          }}
        }
      },
      startDates: {
        $map: {
          input: "$startDates",
          in: {$dateFromString: {
              dateString: "$$this",
              format: "%d.%m.%Y"
          }}
        }
      }
  }},
  {$project: {
      dates: {
        $zip: {
          inputs: [
            {$reverseArray: "$startDates"},
            {$reverseArray: "$endDates"}
          ],
          useLongestLength: true
        }
      }
  }}
])

看看它在playground example号公路上是如何工作的

现在,如果要判断特定日期,可以根据请求的日期向数组$filter再添加一个步长,并用布尔值替换结果:

{$project: {
      res: {
        $toBool: {$size: {
            $filter: {
              input: "$dates",
              cond: {
                $and: [
                  {$gte: [ISODate("2021-12-17T00:00:00Z"), {$first: "$$this"}]},
                  {$or: [
                      {$lt: [ISODate("2021-12-17T00:00:00Z"), {$last: "$$this"}]},
                      {$eq: [{$last: "$$this"}, null]}
                  ]}
                ]
              }
            }
        }}
      }
  }}

看看它在playground example号公路上是如何工作的

Mongodb相关问答推荐

MongoDB - 家庭作业(job)帮助.不确定如何在 mongodb 中访问文档中的变量

MongoDB聚合:如何将查找结果放入嵌套数组中?

查询有关 Go 项目中对象数组的 MongoDb 集合

Mongo 删除最后的文件

删除一对一和一对多引用 - Mongoose

Mongoid 有 Map/Reduce 吗?

你如何在 Kubernetes 上设置 Mongo 副本集?

mongodb 模式设计命名约定

使用 MongoDB 进行分页

$elemMatch 的 MongoDB 索引

ZonedDateTime 与 MongoDB

MongoDB 存储 ObjectId 的数组

如何使用 angular.js 推送通知?

我如何使用 Twitter 的流 api 中的推文并将它们存储在 mongodb 中

Mongodb $lookup 使用 _id 无效果

MongoDB 和 Robomongo: Can't connect (authentication)

show dbs 给出Not Authorized to execute command错误

无法从 mongodb 中删除集合

MongoDB Compass:select distinct field values

有没有办法防止 MongoDB 向集合名称添加复数形式?