我使用mongo db来存储通知,每天午夜运行cron
个作业(job)来挑选旧通知并删除它们.
删除策略具有保留"sourceObjectIdentifier"
和"notificationType"
的每个组合的最旧通知的逻辑.将查询1的聚合输出提供给查询2以形成删除查询.
query 1-query 1-
db.persistentEvent.aggregate([
{
"$match": {
"notificationClass": {"$eq": "category"}
}
},
{
"$group": {
"_id": [
{"sourceObjectIdentifier": "$sourceObjectIdentifier"},
{"notificationType": "$notificationType"}
],
"notificationId": {"$last": "$notificationId"},
"notificationClass": {"$last": "$notificationClass"}
}
},
{
"$project": {
"_id": 0,
"notificationId": 1,
"notificationClass": 1
}
},
{
"$sort": {
"sourceObjectIdentifier": 1,
"notificationType": 1,
"creationTime": -1
}
}
])
query 2-query 2-
{
"deliveryTime": {
"$gt": "$datefrom"
},
"creationTime": {
"$lt": "dateto"
},
"notificationId": {
"$nin": [query_1_output]
}
}
如果集合中的通知数量较少,则此删除逻辑可以很好地工作,但当通知数量在200k或更多时,删除逻辑会花费较长时间.
有人能建议我如何改进查询吗?查询1和查询2可以一起执行吗?