ac360
ac360

Reputation: 7835

How To Get Multiple Counts In One Query?

I have a BlogPost model, and two of its attributes are draft: Boolean and user: String.

Is it possible to get the following counts in one query using mongo's aggregation framework with Mongoose?

BlogPost.count({ user: userID }, function(err, response() {});
BlogPost.count({ user: userID, draft: true }, function(err, response() {});

Upvotes: 0

Views: 1945

Answers (2)

Akshay Dhawle
Akshay Dhawle

Reputation: 157

this is an aggregation query when we have to count more than ten tables data in one query we use it

   const res= await taskModel.aggregate([
            {
                $facet:
                {
                    "count1": [
                        {
                            $match:
                                { user_id: ObjectId(data.user_id) }
                        }, { $count: "mycount" }]
                    ,
                    "count2":
                        [{
                            $match:
                            {
                                $and:
                                    [{ user_id: ObjectId(data.user_id) }, { task_status: 2 }]
                            }
                        },
                        { $count: "mycount" }]
                }
            }])

Upvotes: 1

Neil Lunn
Neil Lunn

Reputation: 151092

The $cond operator is a ternary operator that evaluates a conditional expression to true/false and returns either the second or third arguments respectively depending on the evaluation. Your field in this case is either boolean true/false, so there is no need to test with another operator. You implement this inside the $sum:

BlogPost.aggregate(
    [
        { "$group": {
            "_id": null,
            "total_count": { "$sum": 1 },
            "draft_count": { "$sum": { "$cond": [ "$draft", 1, 0 ] } }
        }
    ],
    function(err,results) {

    }
);

Passing in null to the _id value of group means that you are not "grouping" on any specific document key but are grouping all of the documents in the collection.

Upvotes: 4

Related Questions