简体   繁体   中英

Querying MongoDB for range of data

I am trying to query a range of data that is not organized by months, but does have ordinal values. I have 13 numbered documents in a given year per person (data simplified):

{ "Year" : 2015, "Pts" : 92, "Week" : 1 },
{ "Year" : 2015, "Pts" : 110.3, "Week" : 2 },
{ "Year" : 2015, "Pts" : 104.2, "Week" : 3 },
{ "Year" : 2015, "Pts" : 130.9, "Week" : 4 },
{ "Year" : 2015, "Pts" : 129, "Week" : 5 },
{ "Year" : 2016, "Pts" : 90, "Week" : 1 },
{ "Year" : 2016, "Pts" : 110.5, "Week" : 2 },
{ "Year" : 2016, "Pts" : 106, "Week" : 3 },
{ "Year" : 2016, "Pts" : 150.4, "Week" : 4 },
{ "Year" : 2016, "Pts" : 110, "Week" : 5 },
{ "Year" : 2017, "Pts" : 86.2, "Week" : 1 },
{ "Year" : 2017, "Pts" : 120.2, "Week" : 2 },
{ "Year" : 2017, "Pts" : 111, "Week" : 3 },
{ "Year" : 2017, "Pts" : 105.5, "Week" : 4 }
{ "Year" : 2017, "Pts" : 95.5, "Week" : 5 }

I can't figure out how to grab data from week 3, 2015 through week 3, 2017, for example. When I use the following match pattern, it will only pull weeks 3 and up for all years (weeks 1-2 are missing from the result for 2017 and 2018):

        {
            $match: 
            { 
                Week: { $gte: weekStart, $lte: weekEnd },
                Year: { $gte: startYear, $lte: endYear }
            }
        },

I've tried using $not to try to exclude documents outside of the range, but I get the error unknown top level operator: $not . I've also tried cascading $and statements, but that doesn't work either.

Any help is appreciated!

Something like this should do the trick:

$or : [
 { Year: startYear, Week: { $gte: weekStart} },
 { Year: { $gt: startYear, $lt: endYear } },
 { Year: endYear, Week: { $lte: weekEnd } }  
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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