MongoDB:如何根据日期间隔和匹配间隔中所有日期的更多条件进行查询

标签 mongodb mongodb-query

我有一个 mongo 集合,用于存储有关产品的信息,并且它有一个嵌入式数组,用于按日期存储其可用性。

{
  "product_id": "A",
  "name": "mountain bicycle",
  "cost_per_hour": "$5",
  "availability":[
    {
      "timestamp": ISODate("2018-11-19 18:30:00.000Z"),
      "available": true
    },
    {
      "timestamp": ISODate("2018-12-20 18:30:00.000Z")
      "available": true
    },
    {
      "timestamp": ISODate("2018-12-21 18:30:00.000Z")
      "available": false
    }
  ]
}

我想列出给定日期间隔内所有日期的所有可用产品。

Example: If I query for date between ISODate("2018-11-19 18:30:00.000Z") To ISODate("2018-12-20 18:30:00.000Z") AND available: true, I should get a product with "product_id": "A", since its available on all dates between the date interval.

But If I query between ISODate("2018-11-19 18:30:00.000Z") To ISODate("2018-12-21 18:30:00.000Z") AND available: true, I should NOT get any results since the product is NOT available on all dates in the date range.

我尝试使用 $elemMatch,但返回的产品在至少 1 时间间隔内给定的日期中可用,这是我不想要的。

请指导。

最佳答案

要查找数组字段的所有元素都通过查询的文档,您可以反转查询以查找失败案例(available: false),然后使用 $not仅返回未发生失败情况的文档:

db.test.find({
  availability: {$not: {$elemMatch: {
    timestamp: {$gte: ISODate("2018-11-19 18:30:00.000Z"), 
                $lte: ISODate("2018-12-21 18:30:00.000Z")},
    available: false
  }}}
})

关于MongoDB:如何根据日期间隔和匹配间隔中所有日期的更多条件进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53363092/

相关文章:

java - 如何在Spring Boot中使用elemMatch查询数组的元素,使得数组只有一列并且该列没有字段名?

mongodb - 在 mongo 聚合 $lookup 查询中使用数组第一个字段来匹配文档

c# - MongoDB - 在小型记录集上使用 C# 驱动程序时没有索引错误的 sort() 数据太多

javascript - 使用变量作为 mongodb 中字段名称的一部分?

node.js - 查询时间 mongoose 偶尔需要 3-4 秒

javascript - 如何在 mongodb 中映射对象数组并将字符串值转换为数字?

mongodb - mongodump 错误 "Failed: can' t 创建 session : could not connect to server:"

Mongodb 的 $match 返回同一文档的多次出现

MongoDB 对特定嵌套属性的投影

MongoDB:使用带有 csv 的 MongoImport 仅更新单个字段