Fastest way to count documents in aggregation?

Hello everyone,
For pagination, which is the most appropriate way to count the documents?

Hi,

You can use $facet that enables you do execute multiple aggregation pipelines on the same set of documents.

You can both count the total documents and return pagination results, all in one query.

Here is a good Stack Overflow answer with an example: How to use MongoDB aggregation for pagination? - Stack Overflow.

Thank you @NeNaD . I tried this but still my query is taking time. Is there any way in which I can reduce the query time.

Hi,

Can you add more info to the question? Add your model, the query that you are executing, indexes…

Hi,
So, The query is:

pipeline := []bson.M{
		{"$match": bson.M{"_id": bookingId}},
		{
			"$lookup": bson.M{
				"localField":   "_id",
				"from":         config.BookingTimeLogCol,
				"foreignField": "booking_id",
				"as":           "booking_time_logs",
			}},
		{"$match": bson.M{"booking_time_logs": bson.M{"$not": bson.M{"$size": 0}}}},
		{"$group": bson.M{
			"_id":               "$_id",
			"provider_ids":      bson.M{"$first": "$booking_time_logs.provider_id"},
			"booking_time_logs": bson.M{"$first": "$booking_time_logs"},
			"booking_info":      bson.M{"$push": "$$ROOT"},
		}},
		{"$unwind": "$booking_info"},
		{
			"$lookup": bson.M{
				"localField":   "booking_info.uid",
				"from":         bkconfig.UsersCollection,
				"foreignField": "_id",
				"as":           "customer_info",
			}},
		{"$unwind": "$customer_info"},
		{
			"$lookup": bson.M{
				"localField":   "provider_ids",
				"from":         bkconfig.UsersCollection,
				"foreignField": "_id",
				"as":           "provider_info",
			}},
		{
			"$lookup": bson.M{
				"localField":   "booking_info.address_id",
				"from":         config.AddressCol,
				"foreignField": "_id",
				"as":           "booking_info.booking_location",
			}},
		{"$unwind": bson.M{"path": "$booking_info.booking_location", "preserveNullAndEmptyArrays": true}},

The primary collection is bookings.
I have used booking_id index on booking_time_logs.