Dive into Data Filtering: Querying, Sorting, and Projecting in MongoDB

Welcome back, coding astronauts! Today we'll journey through data retrieval in MongoDB, focusing on querying, sorting, and projecting techniques. Armed with these tools, our navigations through the database universe will become more efficient and precise.

Querying in MongoDB: The Telescope to Your Data Universe
Sorting in MongoDB: Arranging Your Cosmic Data

The act of sorting in MongoDB is akin to ordering stars by their brightness. To establish this order, we use sort(). Whether we are sorting data in ascending (1) or descending (-1) order, the results are neatly organized.

Sorting posts by their likes count is straightforward. Here's how:

JavaScript
// sort all posts by likes count in descending order
Post.find().sort({ likesCount: -1 })
  .then(posts => console.log(posts)) // display sorted posts
  .catch(err => console.error(err)); // handle error

Querying and sorting can be combined for more refined results:

JavaScript
// find posts with more than 10 likes and sort them by likes count in descending order
Post.find({ likesCount: { $gt: 10 } }).sort({ likesCount: -1 }) 
  .then(posts => console.log(posts)) // display sorted posts
  .catch(err => console.error(err)); // handle error
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal