简体   繁体   English

检查匹配查询聚合中是否存在字段 mongodb

[英]check if field exists in match query aggregation mongodb

i have a mongodb collection of events from which i want to get the current availablae events so i am using match query like that我有一个 mongodb 事件集合,我想从中获取当前可用的事件,所以我使用这样的匹配查询

   Event.aggregate([ { $match: { isActive: true, ...matchQuery, startDate:{$lt:today}, endDate:{$gt:today} } },])

the problem is that not all the events in my database have startDate and enDate fields and i want to get those events too, so i want to check if startDate and endDate exists then they should be lt and gt than today if they don't exist and the document match the rest of the query, i want to get it.问题是我的数据库中并非所有事件都有 startDate 和 endDate 字段,我也想获取这些事件,所以我想检查 startDate 和 endDate 是否存在,那么如果它们不存在,它们应该是 lt 和 gt并且文档与查询的 rest 匹配,我想得到它。 i tried this way but doesn't work我试过这种方式但不起作用

{ $match: { isEnabled: true, ...matchQuery, startDate ? {startDate:{$lt:today}}, endDate ?  endDate:{$gt:today} } },
  

thank you谢谢你

So the idea is to fetch all documents where:所以这个想法是获取所有文档,其中:

  1. startDate AND endDate does not exits. startDate AND endDate不存在。

OR或者

  1. today is between the range startDate AND endDate . today在范围startDateendDate之间。

Try this:尝试这个:

let today = new Date();

db.events.aggregate([
    {
        $match: {
            isActive: true,
            $or: [
                {
                    startDate: { $exists: false },
                    endDate: { $exists: false }
                },
                {
                    startDate: { $lt: today },
                    endDate: { $gt: today }
                }
            ]
        }
    }
])

Output: Output:

{
    "_id" : ObjectId("..."),
    "isActive" : true,
    "startDate" : ISODate("2021-03-01T00:00:00.000+05:30"),
    "endDate" : ISODate("2021-03-31T00:00:00.000+05:30")
},
{
    "_id" : ObjectId("..."),
    "isActive" : true
}

Test data:测试数据:

{
    "_id" : ObjectId("..."),
    "isActive" : true,
    "startDate" : ISODate("2021-03-01T00:00:00.000+05:30"),
    "endDate" : ISODate("2021-03-31T00:00:00.000+05:30")
},
{
    "_id" : ObjectId("..."),
    "isActive" : true,
    "endDate" : ISODate("2021-03-31T00:00:00.000+05:30")
},
{
    "_id" : ObjectId("..."),
    "isActive" : true,
    "startDate" : ISODate("2021-03-01T00:00:00.000+05:30")
},
{
    "_id" : ObjectId("..."),
    "isActive" : true
},
{
    "_id" : ObjectId("..."),
    "isActive" : true,
    "startDate" : ISODate("2021-02-01T00:00:00.000+05:30"),
    "endDate" : ISODate("2021-03-03T00:00:00.000+05:30")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM