moaes01
moaes01

Reputation: 67

How can I get total length(count) of all comments inside Post?

Let's say I have this Schema:

const PostSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    text: {
        type: String,
        required: true 
    },
    comments: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: 'users'
            },
            text: {
                type: String,
                required: true
            },
            date: {
                type: Date,
                default: Date.now
            }
        }
    ],
    date: {
        type: Date,
        default: Date.now
    }
});

And let's say I save 10 posts to the database. How can I get total length(count) of all comments they have?

This works only for whole collection of Post. It returns 10.

router.get( '/total', ( req, res ) => {
    Post.estimatedDocumentCount().then( ( totalCount) => {
        res.json( totalCount );
    }).catch( ( err ) => {
        console.log( err );
    });
});

I don't want to use .count() method since it's deprecated.

Thank you

Upvotes: 1

Views: 103

Answers (1)

Jitendra
Jitendra

Reputation: 3185

You can use $group and find total counts of comments as below:

db.collection.aggregate([
    {
        $group: {
            _id: null,
            count : { $sum: { $size: "$comments"}}
        }
    }
])  

Upvotes: 2

Related Questions