我正试图通过以下代码找出如何将aggregate
与猫鼬一起使用:
const Model = db.model(which, schema)
var regex = new RegExp(name, "g")
const query =
Model
.find({
name: regex
})
.where("user_id").equals(req.session.user.id)
if (except)
{
if (Array.isArray(except))
{
query
.where("_id").nin(except)
}
else
{
query
.where("_id").neq(except)
}
}
return await
query
.skip(start)
.limit(finish)
.lean()
.exec()
我想做的是也得到总数(没有限制)。当然,我可以删除skip
和limit
并使用count
,然后再次运行它,但是我认为聚合在这种情况下合适吗?
答案 0 :(得分:1)
您可以尝试以下汇总
db.collection.aggregate([
{ "$facet": {
"data": [
{ "$match": {
"name": { "$regex": name },
"user_id": mongoose.Types.ObjectId(req.session.user.id),
"_id": { "$nin": except }
}},
{ "$skip": start },
{ "$limit": finish }
],
"count": [
{ "$match": {
"name": { "$regex": name },
"user_id": mongoose.Types.ObjectId(req.session.user.id),
"_id": { "$nin": except }
}},
{ "$count": "count" }
]
}}
])
答案 1 :(得分:0)
(链式)要做一次:
Model
.aggregate()
.match({
"name": { "$regex": name },
"user_id": ObjectId(req.session.user.id),
"_id": { "$nin": except }
})
.facet({
"results": [
{ "$skip": start },
{ "$limit": finish },
{
"$project": {
"map_levels": 0,
"template": 0
}
}
],
"count": [
{ "$count": "total" },
]
})
.exec()