Mongodb - 填充项目限制并获取这些项目的总数
Posted
技术标签:
【中文标题】Mongodb - 填充项目限制并获取这些项目的总数【英文标题】:Mongodb - populate with limit on items and get total count of those items 【发布时间】:2020-03-23 05:34:20 【问题描述】:我的查询如下所示:
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 个。
【问题讨论】:
【参考方案1】:您可以使用match、lookup、project 阶段以及slice 和size 运算符尝试以下聚合:
(请注意,lookup 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
]
Playground
【讨论】:
以上是关于Mongodb - 填充项目限制并获取这些项目的总数的主要内容,如果未能解决你的问题,请参考以下文章
通过浏览他/她的所有帖子 MongoDB 获取该用户收到的总喜欢数