5.1 E-commerce queries
5.1.1 Products, categories and reviews
product = db.products.findOne({'slug': 'wheel-barrow-9092'})db.categories.findOne({'_id': product['main_cat_id']})db.reviews.find({'product_id': product['_id']})
find returns a cursor object, whereas findOnereturns a documenta cursor is returned even when you apply a limit:
db.products.find({'slug': 'wheel-barrow-9092'}).limit(1)
sikp, limit, and sort query options
paginate the review document:
db.reviews.find({'product_id': product['_id']}).skip(0).limit(12)
db.reviews.find({'product_id': product['_id']}).sort({'helpful_votes': -1}).limit(12)
page_number = 1product = db.products.findOne({'slug': 'wheel-barrow-9092'})category = db.categories.findOne({'_id': product['main_cat_id']})reviews_count = db.reviews.count({'product_id': product['_id']})reviews = db.reviews.find({'product_id': product['_id']}).skip((page_number - 1) * 12).limit(12).sort({'helpful_votes': -1})
Product listing page
page_number = 1category = db.categories.findOne({'slug': 'gardening-tools'})siblings = db.categories.find({'parent_id': category['_id']})products = db.products.find({'category_id': category['_id']}).skip((page_number - 1) * 12).limit(12).sort({'helpful_votes': -1})
get thes root-level categories
categories = db.categories.find({'parent_id':null})
5.1.2 Users and orders
search user by username and password:
db.users.findOne({'username': 'kbanker','hashed_password': 'bd1cfa194c3a603e7186780824b04419'})
you can limit the fields returned using a projection:
db.users.findOne({'username': 'kbanker','hashed_password': 'bd1cfa194c3a603e7186780824b04419'},{'_id': 1})
the response now consists exclusively of the document’s _id field:
Partial match queries in users
db.users.find({'last_name': 'Banker'})
suppose you know that the user’s last name starts with Ba
db.users.find({'last_name': /^Ba/})
Querying specify ranges
db.users.find({'addresses.zip': {'$gt': 10019, '$lt': 10040}})
5.2 MongoDB’s query language
suggestion:
skim this section and revisit it when you need to writ more advanced queries for your application
