查找数组中可能存在也可能不存在的元素

Find element in an array that may or may not exist

本文关键字:也可能 不存在 元素 存在 数组 查找      更新时间:2023-09-26

我有一个文档,看起来有点像这样:

> db.orders.find()
{
  _id: ObjectId(),
  _reminders: [{
    notified: true,
    timestamp: ISODate(),
    completed: false
  }]
}
{
  _id: ObjectId(),
  _reminders: []
}

我试图找到的是订单集合中的一个文档,其中"提醒"不包含特定时间范围内的提醒,并且未完成。

db.orders.find({
  '_reminders': {
    $elemMatch: {
      completed: false,
      timestamp: { $ne: time }
    }
  }
});

问题是这不会找到一个根本没有任何提醒的订单。

如何查询?

这应该能得到你想要的

db.getCollection('Clock').find({
$or : [
    {
        _reminders : {
                $elemMatch : {
                    timestamp : {
                        $lte : ISODate("2019-07-12T15:35:32.278Z"), 
                        $gte :  ISODate("2012-07-12T15:35:32.278Z") 
                        },
                    completed : false
                }
        }
    },
    {
       _reminders : {$size : 0}     
    },
    {
       _reminders : {$exists : false}
    }
]

})

你应该使用$or查询。

db.orders.find({$or: [ { _reminders: [] }, here_put_your_query_with_time_match ]}) - 它将返回与您的查询匹配的文档和具有空_reminders的文档