简体   繁体   English

MongoDB Aggregation ..对数组进行计数会在javascript上产生输出。 使用nodeJS,猫鼬

[英]MongoDB Aggregation.. Counting inside an array on produce the output on javascript. using nodeJS, mongoose

this is my mongoose schema 这是我的猫鼬图式

    var testSchema = new mongoose.Schema({
    name: String,
    image: String,
    comments: [
        {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Comment"
        }
    ]
});

so every user has a name, picture and comments. 所以每个用户都有名字,图片和评论。 the comments are array. 注释是数组。 basically i have 10 users, with different comments, i want to count how many comments on per user and display it on the html.. 基本上我有10个用户,有不同的评论,我想计算每个用户有多少评论并显示在html上。

i have tried this 我已经试过了

 db.users.aggregate({$project: { count: {$size:"$comments"}}})

it counts the comments per user of all user... how can i output this on the html? 它计算所有用户的每个用户的评论...我如何在html上输出它? and how can i just perform this command on 1 user? 以及如何仅对1个用户执行此命令? not to all user... thanks! 并非所有用户...谢谢!

For finding the number of comments made by a single user, use the following command in mongoose. 要查找单个用户发表的评论数量,请在猫鼬中使用以下命令。

Users.findOne({_id: ObjectId("57cdf6b3fbccf41198389aca")}, function(err, user) {
     if(err) {
       //handle error
     } else if(!user) {
       //no user found
     } else {
       //user found
       if(user.comments) {
           console.log('user comments length', user.comments.length);
       } else {
           console.log('no user comments');
       }
     }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongoDB 聚合:计算数组中的不同字段 - MongoDB Aggregation: Counting distinct fields from array 在Mongodb / Mongoose聚合子集中应用$ cond - Applying $cond inside subset in Mongodb/Mongoose Aggregation JavaScript。 如果总和 == 0,则在数组中查找某个参数的总和以生成弹出窗口 - JavaScript. Find the sum of a certain parameter in an array to produce a popup if that sum == 0 如何使用 mongodb 聚合查找嵌套数组内的值的总和? - How to find the sum of values that are inside a nested array using mongodb aggregation? 我如何使用 mongoose 聚合找到最常出现的用户 ID,它位于 [] 内? Nodejs,Expressjs - How can i find most occuring userId, which lies inside [] using mongoose aggregation ?? Nodejs, Expressjs mongoDB(在nodeJS中)聚合管道返回空数组 - mongoDB (in nodeJS) aggregation pipleine returns empty array 使用Javascript Mongodb驱动程序进行聚合 - Using Javascript Mongodb driver for Aggregation 如何在 javascript 中迭代 var。 数组里面的数组 - How to iterate var in javascript. Array inside array 使用Javascript从MongoDB返回中提取值。 - Extracting a value from a MongoDB return, using Javascript. 使用mongoose将javascript数组插入mongodb时出错 - Error while inserting javascript array to mongodb using mongoose
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM