如何在MongoDB中获取今天生日的用户列表 [英] How to get list of users who's birthday is today in MongoDB
问题描述
我在 mongo 集合中有带有出生日期的文件列表.我们有前端,用户可以在其中添加复杂的数据条件以获得像
I am having the list of documents with date of birth in mongo collection. We are having the front end where user can add the complex conditions on the data to get the result like
(user.dob isToday AND user.score > 1000) OR (user.dob isTomorrow AND user.score > 2000)
除了日期类型,我可以将上述条件转换为相应的 mongo 查询,如 {"score" : { $gt: 1000}}
.
Other than date type, I am able to convert the above conditions to corresponding mongo query like {"score" : { $gt: 1000}}
.
在生日情况下,我们必须使用 mongo 支持的月份和月份的日期查询数据库,仅使用聚合,这对我的上述用例没有帮助.
In case of birthday condition, we have to query the DB with day of the month and month of the year which is supported in mongo only by using aggregate which will not help for my above use case.
有人有什么建议吗?想法?
Anyone have suggestions? Ideas?
推荐答案
您可以使用带有 $dayOfYear
运算符的聚合框架.我假设生日存储在字段 birthday
中,并且有一个名为 name
的字段:
You can use the aggregation framework with the $dayOfYear
operator. I have assumed that the birth day is stored in the field birthday
and that there is a field called name
:
db.data.aggregate(
[
{
"$project" : {
"_id" : 0,
"name" : 1,
"birthday" : 1,
"score" : 1,
"todayDayOfYear" : {
"$dayOfYear" : new Date()
},
"birthDayOfYear" : {
"$dayOfYear" : "$birthday"
}
}
},
{
"$project" : {
"name" : 1,
"birthday" : 1,
"score" : 1,
"isBirthDay" : {
"$eq" : [
"$todayDayOfYear",
"$birthDayOfYear"
]
}
}
},
{
"$match" : {
"isBirthDay" : true,
"score" : { $gt: 100}
}
}
]
)
这篇关于如何在MongoDB中获取今天生日的用户列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!