Using a basic query vs aggregation pipeline to get same results

I can’t find anywhere in the MongoDB docs which explains whether basic queries are the better choice over aggregation pipelines for a straightforward scenario where I’m not doing any groupings or transformations.

For example, suppose I have a large collection “Books” (5million docs) with the following index: { published: 1, title: 1, date: 1}.

Would it be better/faster for me to use this basic query:

db.Books.find(
    { "published": true, "metadata.xyz": "testValue" },
    { "title": 1, "author": 1},
    { "sort": { "title": 1 }, "skip": 5, "limit": 10 }
);

or this aggregation pipeline:

db.Books.aggregate([
    { $match: {"published": true, "metadata.xyz": "testValue"} },
    { $project: {"title": 1, "author": 1} },
    { $sort: { "title": 1 } },
    { $skip: 5 },
    { $limit: 10 },
]);

to get my results? (I am not able to index the metadata field due to its wide variation of values)

If possible, please share a reference to documentation that explains why one is better/worse than the other for the above situation (or if you’re an official MongoDB employee, that works too)

1 Like

IFind() and aggregate() will produce the same performance because MongoDB (since 3.6) runs them through the same query engine: $match, $project, $sort, $skip, $limit in aggregation are internally optimized the same way as find filters, projections, and sorts. For simple lookups without transformations, find() is usually preferred since it’s more concise and slightly less overhead, but if you anticipate extending the query later (adding groupings, lookups, computed fields, etc.) then starting with aggregation is fine. The key performance factor here is that metadata.xyz is unindexed, so MongoDB must scan documents anyway; your {published, title, date} index only helps with published + title for sorting. Reference: MongoDB docs on aggregation vs find

1 Like

Thanks for clarifying this. However, the link anchor /#comparison-to-find at the end of your linked documentation does not point to anything. Are you sure you pasted the correct link? (I don’t see anything regarding find() on the page you linked as-is)