我正在创建一个 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
欢迎任何帮助。
最佳答案
假设生日字段存储为Date或ISODate类型,您可以使用聚合框架进行正确的比较。我认为它会比启动 javascript shell 的 $where 更快。
// 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}}
] )
关于javascript - MongoDB $where 可选字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322349/