Lab 2.1 Using Indexes to Sort

I do not see the SORT_KEY_GENERATOR stage in the following query execution stats although it does not use the index for sorting.

db.people.explain("executionStats").find({"address.city": "West Cindy" }).sort({"address.city": -1})
{
	"queryPlanner" : {
		"plannerVersion" : 1,
		"namespace" : "myFirstDatabase.people",
		"indexFilterSet" : false,
		"parsedQuery" : {
			"address.city" : {
				"$eq" : "West Cindy"
			}
		},
		"winningPlan" : {
			"stage" : "SORT",
			"sortPattern" : {
				"address.city" : -1
			},
			"memLimit" : 33554432,
			"type" : "simple",
			"inputStage" : {
				"stage" : "COLLSCAN",
				"filter" : {
					"address.city" : {
						"$eq" : "West Cindy"
					}
				},
				"direction" : "forward"
			}
		},
		"rejectedPlans" : [ ]
	},
	"executionStats" : {
		"executionSuccess" : true,
		"nReturned" : 99,
		"executionTimeMillis" : 30,
		"totalKeysExamined" : 0,
		"totalDocsExamined" : 50474,
		"executionStages" : {
			"stage" : "SORT",
			"nReturned" : 99,
			"executionTimeMillisEstimate" : 15,
			"works" : 50576,
			"advanced" : 99,
			"needTime" : 50476,
			"needYield" : 0,
			"saveState" : 50,
			"restoreState" : 50,
			"isEOF" : 1,
			"sortPattern" : {
				"address.city" : -1
			},
			"memLimit" : 33554432,
			"type" : "simple",
			"totalDataSizeSorted" : 41132,
			"usedDisk" : false,
			"inputStage" : {
				"stage" : "COLLSCAN",
				"filter" : {
					"address.city" : {
						"$eq" : "West Cindy"
					}
				},
				"nReturned" : 99,
				"executionTimeMillisEstimate" : 13,
				"works" : 50476,
				"advanced" : 99,
				"needTime" : 50376,
				"needYield" : 0,
				"saveState" : 50,
				"restoreState" : 50,
				"isEOF" : 1,
				"direction" : "forward",
				"docsExamined" : 50474
			}
		}
	},
	"serverInfo" : {
		"host" : "mongodblearning-shard-00-02.beayr.mongodb.net",
		"port" : 27017,
		"version" : "4.4.6",
		"gitVersion" : "72e66213c2c3eab37d9358d5e78ad7f5c1d0d0d7"
	},
	"ok" : 1,
	"$clusterTime" : {
		"clusterTime" : Timestamp(1622008226, 21),
		"signature" : {
			"hash" : BinData(0,"qRKyDJSKsCe4RLNWBqGpfSdDl4w="),
			"keyId" : NumberLong("6965249095006945283")
		}
	},
	"operationTime" : Timestamp(1622008226, 21)

Hi @Nabarun_Bhowmick,

Looking at the winningPlan, we can deduce that:

  1. First there was a COLLSCAN stage which indicates a Collection Scan to find the address.city with values West Cindy.
  2. Then the SORT stage indicates that the index is not used to obtain the sort order.

Please feel free to reach out if you have any additional questions.

Kind Regards,
Sonali Mamgain

My 2 cents on your example:

Sorting on the same field for which you do a find for a single value would be a waste of resources.