Database Reference
In-Depth Information
In some situations you may want to specify fields to exclude, instead. For instance,
this topic's user document contains shipping addresses and payment methods, but
you don't usually need these. To exclude them, add those fields to the projection with
a value of 0:
db.users.find({}, {addresses: 0, payment_methods: 0})
In addition to including and excluding fields, you can also return a range of values
stored in an array. For example, you might want to store product reviews within the
product document itself. In this case, you'd still want to be able to paginate those
reviews, and for that you could use the $slice operator. To return the first 12 reviews,
or the last 5, you'd use $slice like so:
db.products.find({}, {reviews: {$slice: 12}})
db.products.find({}, {reviews: {$slice: -5}})
$slice can also take a two-element array whose values represent numbers to skip and
limit, respectively. Here's how to skip the first 24 reviews and limit the number of
reviews to 12:
db.products.find({}, {reviews: {$slice: [24, 12]}})
Finally, note that using $slice won't prevent other fields from being returned. If you
want to limit the other fields in the document, you must do so explicitly. For example,
here's how you can modify the previous query to return the reviews and the review rat-
ing only:
db.products.find({}, {reviews: {$slice: [24, 12]}, 'reviews.rating': 1})
S ORTING
You can sort any query result by one or more fields in ascending or descending order.
A simple sort of reviews by rating, descending from highest to lowest, looks like this:
db.reviews.find({}).sort({rating: -1})
Naturally, it might be more useful to sort by helpfulness and then by rating:
db.reviews.find({}).sort({helpful_votes:-1, rating: -1})
In compound sorts like this, the order does matter. As noted elsewhere, JSON entered
via the shell is ordered. Since Ruby hashes aren't ordered, you indicate sort order in
Ruby with an array of arrays, which is ordered:
@reviews.find({}).sort([['helpful_votes', -1], [rating, -1]])
The way you specify sorts in MongoDB is straightforward, but two topics, discussed
elsewhere, are essential to a good understand of sorting. The first is knowing how to
sort according to insertion order using the $natural operator. This is discussed in
chapter 4. The second, and more relevant, is knowing how to ensure that sorts can
efficiently use indexes. We'll get to that in chapter 8, but feel free to skip ahead if
you're heavily using sorts now.
Search WWH ::




Custom Search