top of page

Using the find() method- Part 13

We’ve already seen how to do some basic find() operations. Let’s look at some other items here we might want to do in order to adjust what we get back. We want to change things a little bit. For example, let’s say I would like to sort my responses, db.products.find(). Now within that find(), I can put any criteria I like, but since we only have few documents, I’m going to get back all of them. However, I’m going to type in sort, open parentheses, and I can sort on any value in there I like. I’m going to sort these based on price, and the way I do that is putting a one value there. That’s saying to use that value as the sorting criteria. And you see all of my responses are sorted from the lowest price to the highest, so that’s pretty helpful and useful. In some cases, you’ll want to limit your responses. For example, I have several items here, and maybe I only want to see the first two.

db.products.find().sort({price.1})

and again within that find() you can use any of the previous criteria we’ve seen, the greater than, the less than, anything you like. But let’s say I’m still getting back a lot of records, type limit. And what would you like to limit it to? I’m going to limit mine to three. So I get back the first three records that match, simple as that.

db.products.find().limit(3)

db.products.find({$or:[{“brand” : “ACME”},{“brand” : “Acer”}]})

Let’s clear the screen and show you one more. You will notice in every one of the queries we’ve looked at so far, we get back all of the field values. We’re getting back type and brand and price. What if I just would like to know one or two of those fields? Well let’s take a look at that. First of all, that is what we normally see when looking at all of them. What if in one particular circumstance I really do not care about price or page count, and I just want to know the title, how can I do that? This is called a projection –db.products.find, open. Now I’m not going to give it any find() criteria; I could, and if you put it in there, it would limit the records, but regardless of whether I do or don’t, I’m going to put a comma, then I’m going to enumerate those values I’d like to see. In this case, I just care about the brand, close it, and it gives me back all of my titles.

db.products.find({},{price:1})

RECENT POSTS

FEATURED POSTS

Check back soon
Once posts are published, you’ll see them here.

FOLLOW US

  • Grey Facebook Icon
  • Grey Twitter Icon
  • Grey Instagram Icon
  • Grey Google+ Icon
  • Grey Pinterest Icon
bottom of page