我已经编写了一个MongoDB聚合查询,它使用了许多阶段。最后,我希望查询以以下格式返回我的数据:
{
data: // Array of the matching documents here
count: // The total count of all the documents, including those that are skipped and limited.
}
我将使用skip和limit特性来最终减少结果。不过,我想知道退回文件的数量
我跳过并限制它们。可能,管道阶段必须发生在
$match
$skip
和
$limit
阶段。
下面是我目前编写的查询(它位于express.js路径中,这就是为什么我使用这么多变量的原因:
const {
minDate,
maxDate,
filter, // Text to search
filterTarget, // Row to search for text
sortBy, // Row to sort by
sortOrder, // 1 or -1
skip, // rowsPerPage * pageNumber
rowsPerPage, // Limit value
} = req.query;
db[source].aggregate([
{
$match: {
date: {
$gt: minDate, // Filter out by time frame...
$lt: maxDate
}
}
},
{
$match: {
[filterTarget]: searchTerm // Match search query....
}
},
{
$sort: {
[sortBy]: sortOrder // Sort by date...
}
},
{
$skip: skip // Skip the first X number of doucuments...
},
{
$limit: rowsPerPage
},
]);