我有一个查询如下:
const articles = await Article.find(query)
.populate({
path: 'votedUsers', // array of users id
select: 'title name username',
options: {
limit: 3,
sort: { createdAt: -1 },
},
})
.exec()
结果:
[
{
title: 'Article title',
votedUsers: [,,], // array of populated users with limit of 3
totalCountVoted: 200 // need to add this field
}
]
我想查找文章并填充votedUsers
属性,但限制为3个用户,但同时
我需要知道votedUsers
属性中有多少个ID。
例如,可能有200位用户对该文章进行了投票,但我只需要知道数字并只填充其中的3位即可。
答案 0 :(得分:1)
您可以使用match,lookup,project阶段以及slice和size运算符尝试以下聚合:
(请注意,from中的“ users”值必须是物理集合名称。)
app.get("/article", async (req, res) => {
const data = await Article.aggregate([
{
$match: {
category: "Category1"
}
},
{
$lookup: {
from: "users",
localField: "votedUsers",
foreignField: "_id",
as: "users"
}
},
{
$project: {
title: 1,
votedUsers: { $slice: ["$users", 3] },
totalCountVoted: { $size: "$users" }
}
}
]);
res.send(data);
});
这将为您提供如下结果:
[
{
"_id": "5dded78f8f30c402b0fac309",
"title": "Article1",
"votedUsers": [
{
"_id": "5dded60a84523642bc27f511",
"__v": 0,
"name": "User1"
},
{
"_id": "5dded61384523642bc27f512",
"__v": 0,
"name": "User2"
},
{
"_id": "5dded61b84523642bc27f513",
"__v": 0,
"name": "User3"
}
],
"totalCountVoted": 8
},
{
"_id": "5dded7c18f30c402b0fac30a",
"title": "Article2",
"votedUsers": [
{
"_id": "5dded61b84523642bc27f513",
"__v": 0,
"name": "User3"
},
{
"_id": "5dded63c84523642bc27f514",
"__v": 0,
"name": "User4"
},
{
"_id": "5dded64484523642bc27f515",
"__v": 0,
"name": "User5"
}
],
"totalCountVoted": 8
}
]