Time for action — finding the highly ranked books

Suppose we add the rank field to the books, our book object will look something as follows:

{
"_id" : ObjectId("4e870521fed0eb0f97000002"),
"rank" : 10
}

Now, if we want to search for all books having a rank in the top 10 ranks, we can fire the following query:

> db.books.find({ "rank" : { $lte : 10 } } )

You can add more operators in the same hash too. For example, if we want to find books in the top ten but not the top ranked book (that is, rank != 1), we can do the following:

> db.books.find({ "rank" : { $lte : 10, $ne : 1 } } )

Have a go hero — find books via rank

Why don't you give this a shot?

  • Find books which have a rank between 5 and 10
  • Find books before and after a particular date

Checking presence using $exists

As MongoDB is schema free, there are times when we want to check the presence of some field in a document. For example, over the years, our schema for books evolved and we added some new fields. If we want to take a specific action on books that only have these new fields, we may need to check if these fields exist.

Suppose we want to search only for those books that have the rank field in them, it can be done as follows:

> db.books.find({ "rank" : { $exists : 1} })
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.186.127