如何聚合数组中ObjectID的出现次数?

我有两个集合; userscommunities 。 我的用户可以链接到许多社区,所以我已经将linkedCommunities作为用户架构中的数组来链接,如下所示:

 const userSchema = new Schema({ linkedCommunities: [ { type: mongoose.Schema.ObjectId, ref: 'Community' } ] }); 

在我的communities视图中,我想显示链接到每个社区的users数量,因此它会显示如下内容:

 | Community | Number of users | | --------- | --------------- | | Community 1 | 45 | | Community 2 | 78 | | Community 4 | 107 | 

理想情况下,当我在Community模型上查找时,我想要一个名为linkedUserCount的字段。

我敢肯定,我可以用某种方式来实现这一点,但我正在努力寻找合适的pipe道运营商和订单。

您可以使用以下mongodb查询来获得所需的结果:

 db.users.aggregate( [ { $unwind : "$linkedCommunities" }, { $group : { _id : "$linkedCommunities", count: { $sum: 1 } } }, { $project: { _id: 0, community: "$_id", count: "$count" } } ] ) 

试试看,如果您有任何问题,请告诉我。

这里也许可以帮助你,

 users.aggregate([ { $lookup: { from: "Community", localField: "linkedCommunities", foreignField: "_id", as: "linkedcommunities" }} ,{ $unwind: "$linkedCommunities" }, { $group : { _id : "$linkedCommunities", count: { $sum: 1 } } }, { $project: { _id: 0, community: "$_id", count: "$count" } }]}