Home > Software design >  Get project fields from query using optional values [mongoDb]
Get project fields from query using optional values [mongoDb]

Time:07-15

I have the following query which gets the data that has date.start_time greater than new Date().getTime() - 1000 * 60 * 60 * 24 * 365

Here is the query:

query = EoCHistory.find({
    $and: [
        { $or: ors },
        { 'date.start_time': { $gt: new Date().getTime() - 1000 * 60 * 60 * 24 * 365 } },
    ],
});

I want to also include all those entries that DO NOT have date.start_time

How can this be achieved?

What I tried is:

query = EoCHistory.find({
    $and: [
        { $or: ors },
        {
            'date.start_time': {
                $or: [{ $gt: new Date().getTime() - 1000 * 60 * 60 * 24 * 365 }, undefined],
            },
        },
    ],
});

And

query = EoCHistory.find({
    $and: [
        { $or: ors },
        {
            'date.start_time': {
                $or: [{ $gt: new Date().getTime() - 1000 * 60 * 60 * 24 * 365 }, { $exists: false }],
            },
        },
    ],
});

CodePudding user response:

You have the right idea by just wrapping it with an additional $or you just have a minor syntax error, try this:

query = EoCHistory.find({
    $and: [
        { $or: ors },
        {
            $or: [
                {
                    'date.start_time': { $gt: new Date().getTime() - 1000 * 60 * 60 * 24 * 365 },
                },
                {
                    'date.start_time': { $exists: false },
                },
            ],
        },
    ],
});
  • Related