对具有ID数组的模型执行单个查询计数?

时间:2019-07-22 18:03:59

标签: mongoose

我有这段代码,一本书可以有很多注释,我想将它们的数量放在数组中

const bookCommentsLoader = new DataLoader(async bookIds => {
  const comments = await Comment.count({
    bookId: { $in: bookIds }
  })
  ...
})

graphql数据加载器的问题在于,返回时,id的结果和长度必须匹配,所以我希望它返回以下内容:

model id-> ['1','3','12'] must return model counts like [5,7,1]

我不想使用循环提示,它将发送多个查询,我想使用单个查询,帮助吗?

1 个答案:

答案 0 :(得分:0)

https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum

您将使用汇总

var aggregatePipeline = [
    {$group: {_id: "$bookId", numOfComments: {$sum: 1}}
];


Comments.aggregate(aggregatePipeline, (error, results) => {
    // results comes out to be [{_id: bookId, numOfComments: Number}, ....]
    // From here, you can map the array to the format you wish
    var formattedArray = results.map(o => return(o.numOfComments))

    console.log(formattedArray);
});