MongoDB $ where可选字段

时间:2013-05-01 16:35:24

标签: javascript mongodb

我正在创建一个MongoDB查询,返回今天生日的用户,所以我在$ where语句中创建了这个JS函数:

function() {
    if (! this.birthday.getMonth) {return false;}

    return this.birthday.getMonth() == 1
    && this.birthday.getDate() == 1
}

不幸的是,如果没有为文档设置生日字段,那么if语句似乎不起作用,因为我有错误:

JS Error: TypeError: this.birthday has no properties nofile_18

欢迎任何帮助。

2 个答案:

答案 0 :(得分:0)

假设生日字段存储为Date或ISODate类型,您可以使用聚合框架进行正确的比较。我认为它会比启动javascript shell的$更快。

// construct "thisMonth" variable which is current month as a number
// and thisDay which is current date of the month as a number
> var thisMonth = 5;
> var thisDay = 1;
> db.people.aggregate( [ 
        {$project:{month:{$month:"$birthday"}, date:{$dayOfMonth:"$birthday"}}},
        {$match: {month:thisMonth, date: thisDay}}
  ] )

答案 1 :(得分:0)

我终于通过$exists解决了$ where语句前面的问题。它现在可以正常工作,即使没有'生日'字段。

相关问题