您可以使用聚合框架来过滤文档。带有 $match 和 $redact 步骤的管道将执行过滤。
考虑运行以下聚合操作,其中 $redact 允许您使用 $cond 运算符处理逻辑条件并使用系统变量 @987654325 @“保留”逻辑条件为真的文档或$$PRUNE“删除”条件为假的文档。
此操作类似于具有 $project 管道,该管道选择集合中的字段并创建一个新字段来保存逻辑条件查询的结果,然后是后续 @ 987654328@,除了 $redact 使用更高效的单个流水线阶段:
var moment = require('moment'),
last2hours = moment().subtract(2, 'hours').toDate(),
last24hours = moment().subtract(24, 'hours').toDate();
MongoClient.connect(config.database)
.then(function(db) {
return db.collection('MyCollection')
})
.then(function (collection) {
return collection.aggregate([
{ '$match': { 'response_log.created_at': { '$gt': last2hours } } },
{
'$redact': {
'$cond': [
{
'$lt': [
{
'$size': {
'$filter': {
'input': '$response_log',
'as': 'res',
'cond': {
'$lt': [
'$$res.created_at',
last24hours
]
}
}
}
},
3
]
},
'$$KEEP',
'$$PRUNE'
]
}
}
]).toArray();
})
.then(function(docs) {
console.log(docs)
})
.catch(function(err) {
throw err;
});
说明
在上述聚合操作中,如果执行第一个$match管道步骤
collection.aggregate([
{ '$match': { 'response_log.created_at': { '$gt': last2hours } } }
])
返回的文档将是从当前时间开始的最近 2 小时内没有 "response_log.created_at" 的文档,其中使用 subtract 使用 momentjs 库创建变量 last2hours API。
前面带有 $redact 的管道将使用 $cond 三元运算符进一步过滤上面的文档,该三元运算符评估使用 的逻辑表达式>$size 获取计数,$filter 返回一个过滤后的数组,其中包含与其他逻辑条件匹配的元素
{
'$lt': [
{
'$size': {
'$filter': {
'input': '$response_log',
'as': 'res',
'cond': { '$lt': ['$$res.created_at', last24hours] }
}
}
},
3
]
}
如果条件为真,
$$KEEP 文档或 $$PRUNE“删除”评估条件为假的文档。