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.
First, we'll delve into querying, which you can think of as using a telescope to pinpoint a star. In our case, find()
in Mongoose acts as our telescope. Suppose we have 'users' posting 'thoughts', represented by a Post
model, and we want to find posts with likesCount
exceeding 10. Here's how we can accomplish this:
JavaScript1const mongoose = require('mongoose'); //import Mongoose 2 3const Post = mongoose.model('Post', new mongoose.Schema({ 4 text: String, // post text 5 authorId: String, // author's id 6 likesCount: Number // count of likes 7})); 8 9// query posts with more than 10 likes 10Post.find({ likesCount: { $gt: 10 } }) 11 .then(posts => console.log(posts)) // display posts 12 .catch(err => console.error(err)); // handle error
In the above code, $gt
is an operator that finds numbers greater than 10.
In MongoDB, there exist special keywords that enable us to carry out actions such as comparing values or checking ranges. Here are a few of them:
$eq
: Matches values that are equal to a specified value.$gt
: Matches values that are greater than a specified value.$lt
: Matches values that are less than a specified value.$regex
: Provides pattern matching capabilities to fetch data based on specific patterns. For instance, the /substring/
pattern matches any document where the specified field contains the substring "substring".Each of these operators must be nested within a set of curly braces ({}
) and prefixed with a $
sign.
Let's consider the task of finding posts containing the word coding
.
JavaScript1// query posts containing 'coding' 2Post.find({ text: { $regex: 'coding', $options: 'i' } }) 3 .then(posts => console.log(posts)) // display posts 4 .catch(err => console.error(err)); // handle error
The $options: 'i'
tag helps perform case-insensitive searching.
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:
JavaScript1// sort all posts by likes count in descending order 2Post.find().sort({ likesCount: -1 }) 3 .then(posts => console.log(posts)) // display sorted posts 4 .catch(err => console.error(err)); // handle error
Querying and sorting can be combined for more refined results:
JavaScript1// find posts with more than 10 likes and sort them by likes count in descending order 2Post.find({ likesCount: { $gt: 10 } }).sort({ likesCount: -1 }) 3 .then(posts => console.log(posts)) // display sorted posts 4 .catch(err => console.error(err)); // handle error
Finally, think of projecting as analogous to using a flashlight in the dark to focus on particular objects. In our case, select()
acts as that flashlight, illuminating the required data fields in our documents.
For instance, if you're interested only in the text
of the post and the authorId
:
JavaScript1// find all posts and project only 'text' and 'authorId' 2Post.find().select('text authorId') 3 .then(posts => console.log(posts)) // display projected posts 4 .catch(err => console.error(err)); // handle error
A more practical option would be to use Post.find().select('text authorId -_id')
: The minus sign (-) before _id
indicates that we want to exclude the _id
field from the results. By default, MongoDB always includes the _id
field, so we need to explicitly exclude it if we don't want it to appear.
Summing it up, we have mastered querying with find()
, sorting with sort()
, and projecting with select()
. We strongly recommend practicing with real-life data manipulations to solidify these MongoDB skills. With your newly-built data telescope, you're ready to navigate confidently through the MongoDB cosmos! Safe travels!