查询MongoDB的数据范围

时间:2018-09-02 21:17:04

标签: javascript node.js mongodb

我正在尝试查询不是按月组织的但具有序数值的数据范围。在给定的年份中,我每人有13个编号文件(简化数据):

{ "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 }

例如,我不知道如何获取2015年第3周到2017年第3周的数据。当我使用以下匹配模式时,它只会拉长第3周并持续所有年份(2017和2018年的结果缺少1-2周):

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

我尝试使用$ not尝试排除范围之外的文档,但是出现错误unknown top level operator: $not。我还尝试了级联$ and语句,但这也不起作用。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

类似这样的事情应该可以解决:

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