skip to content
Alvin Lucillo

Optimizing aggregation with index

/ 1 min read

Creating an index is a basic performance optimization one can do with mongodb. Let’s demo that one with these collections. dtls is related to users by userid

test > db.users.find({})[{ _id: ObjectId("681320acfe3a48b161544ca7"), name: "julie" }];
test >
	db.dtls.find({})[
		{
			_id: ObjectId("68132100fe3a48b161544ca8"),
			info: "somedtls",
			userid: ObjectId("681320acfe3a48b161544ca7"),
		}
	];

With lookup aggregation stage, we can join the two. Using explain command, we can see in the output (look for indexesUsed: []) that there’s no index used.

 db.users.aggregate([{$lookup: {from: "dtls", localField: "_id", foreignField: "userid", as: "dtls"}}, {$project: {"name": 1, "dtls.info": 1}}]).explain("allPlansExecution")

When we create an index, we can see that the property will be filled with the new index: indexesUsed: [ 'userid_1' ],

db.dtls.createIndex({userid: 1})
test> db.dtls.getIndexes()
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { userid: 1 }, name: 'userid_1' }
]