Tim Hysniu
Tim Hysniu

Reputation: 1540

MongoDB aggregate and project total number of results

I am using db.collection.aggregate() using the following query below. I get the results fine, where projected fields are exactly those specified below. I want to also get total number of documents matching this criteria.

    db.collection.aggregate([
        { $match: { "age": {"$gte": 20, "$lte": 30}} },
        { $lookup: { from: "photos", localField: "post_id", foreignField: "post_id", as: "photos"} },
        { $project: {
            "title": 1,
            "photos.path": 1,
            "age": 1,
            "city": 1,
            "location": 1,
            "post_id": 1,
            "score": { "$meta": "textScore"}
        } },
        { $sort: { score: { $meta: "textScore" } } },
        { $skip: 0 },
        { $limit: 30 },
    ])

After some research I found that I need to add the option below:

      { $group: { _id: null, count: { $sum: 1 } } }

However, with this added I am now getting this as a response:

      { "_id" : null, "count" : 400 }

The count is correct, but the fields that I want to project are no longer there. Is there a way to get the count AND the fields I want to project in one result? Or do I have to run two separate queries, one for count and one for fields I want to project?

Upvotes: 3

Views: 3490

Answers (2)

libik
libik

Reputation: 23049

Yes, it is possible, the grouped documents can be accessed with $push

Upvotes: 2

Shantanu Madane
Shantanu Madane

Reputation: 615

Add this to your aggregation Pipeline

{ $group: { _id: {"title":"$title","age":"$age","city":"$city","location":"$location","post_id":"$post_id","score":"$score"}, count: { $sum: 1 } } })

Upvotes: 0

Related Questions