首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Mongo获取多个查询

从Mongo获取多个查询
EN

Stack Overflow用户
提问于 2020-08-26 02:22:44
回答 1查看 35关注 0票数 0

在NodeJS中,有没有更好/更优的方法从Mongo中获取多个查询?我为每个用户循环运行这段代码,所以当我的用户群增长时,我担心这段代码的性能和可靠性。

代码语言:javascript
复制
const cron = require('node-cron');
cron.schedule(process.env.SCHEDULE_TIME, async () => calculateUserHonors(), {
  scheduled: true,
  timezone: 'Europe/Prague',
});

const calculateUserHonors = async () => {
 // for loop for every user in database
let pollVotesCount, commentVotesCount, sharesCount, commentsCount, blogCount;
const pollVotesPromise = getPollVoteCount(dbClient, userId);
const commentVotesPromise = getCommentVotesCount(dbClient, userId);
const sharesPromise = getShareLinkCount(dbClient, userId);
const commentsPromise = getCommentedCount(dbClient, userId);
const blogPromise = getBlogCount(dbClient, userId);
Promise.all([pollVotesPromise, commentVotesPromise, sharesPromise, commentsPromise, blogPromise]).then((values) => {
  pollVotesCount = values[0];
  commentVotesCount = values[1];
  sharesCount = values[2];
  commentsCount = values[3];
  blogCount = values[4];
});

const getPollVoteCount = async (dbClient, userId) => dbClient.db().collection('poll_votes').find({ user: userId }).count();

const getCommentVotesCount = async (dbClient, userId) => dbClient.db().collection('comment_votes').find({ 'user.id': userId }).count();

const getShareLinkCount = async (dbClient, userId) => dbClient.db().collection('link_shares').find({ user: userId }).count();

const getCommentedCount = async (dbClient, userId) => dbClient.db().collection('comments').find({ 'user.id': userId }).count();

const getBlogCount = async (dbClient, userId) => dbClient.db().collection('items').find({ 'info.author.id': userId }).count();
EN

回答 1

Stack Overflow用户

发布于 2020-08-26 02:46:43

您应该查看聚合管道:https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

例如,要获取poll_votes

代码语言:javascript
复制
dbClient.db().collection('poll_votes').aggregate([
    { $group: { _id: '$user', count: { $sum: 1 } } },
    { $addFields: { user: '$_id', pollVotes: '$count' } }
]);

您将获得一个包含每个用户的投票结果的数组。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63584970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档