Friday, October 16, 2020

Mongo DB - Selecting Data

The following query will fetch the documents where the author name is equal to 'Anonymous'.

db.Book.find({author: "Anonymous"});

Find books priced below Rs 200 /-.

db.Books.find({price: {$lt: 200}});

Find books priced above Rs 200 /-.

db.Books.find({price: {$gt: 200}});

The following query will fetch the documents where the title of a book has the word 'earn'.

db.Book.find({title: /earn/});

The following query will fetch the documents where the title of a book starts with the word 'Learn'.

db.Book.find({title: /^Learn/});

Now let us see how to combine multiple filters. The below example returns documents where the title of the book starts with the word 'Learn' and also the price is less than Rs 200 /-. We will be using a comma (',') to combine multiple filters.

db.Books.find({title: /^Learn/}, {price: {$lt: 200}});

The next query can be used to sort results. The following query sorts all book by price in ascending order. Note that '1' implies an ascending order, while '-1' would imply a descending order.

db.Books.find({}).sort({price: 1});

Cheers.

No comments:

Post a Comment