5.1 E-commerce queries

5.1.1 Products, categories and reviews

  1. product = db.products.findOne({'slug': 'wheel-barrow-9092'})
  2. db.categories.findOne({'_id': product['main_cat_id']})
  3. db.reviews.find({'product_id': product['_id']})

find returns a cursor object, whereas findOnereturns a document
a cursor is returned even when you apply a limit:

  1. db.products.find({'slug': 'wheel-barrow-9092'}).limit(1)

sikp, limit, and sort query options

paginate the review document:

  1. db.reviews.find({'product_id': product['_id']}).skip(0).limit(12)
  1. db.reviews.find({'product_id': product['_id']})
  2. .sort({'helpful_votes': -1})
  3. .limit(12)
  1. page_number = 1
  2. product = db.products.findOne({'slug': 'wheel-barrow-9092'})
  3. category = db.categories.findOne({'_id': product['main_cat_id']})
  4. reviews_count = db.reviews.count({'product_id': product['_id']})
  5. reviews = db.reviews.find({'product_id': product['_id']}).
  6. skip((page_number - 1) * 12).
  7. limit(12).
  8. sort({'helpful_votes': -1})

Product listing page

  1. page_number = 1
  2. category = db.categories.findOne({'slug': 'gardening-tools'})
  3. siblings = db.categories.find({'parent_id': category['_id']})
  4. products = db.products.find({'category_id': category['_id']})
  5. .skip((page_number - 1) * 12)
  6. .limit(12)
  7. .sort({'helpful_votes': -1})

get thes root-level categories

  1. categories = db.categories.find({'parent_id':null})

5.1.2 Users and orders

search user by username and password:

  1. db.users.findOne({
  2. 'username': 'kbanker',
  3. 'hashed_password': 'bd1cfa194c3a603e7186780824b04419'})

you can limit the fields returned using a projection:

  1. db.users.findOne({
  2. 'username': 'kbanker',
  3. 'hashed_password': 'bd1cfa194c3a603e7186780824b04419'},
  4. {'_id': 1})

the response now consists exclusively of the document’s _id field:
image.png

Partial match queries in users

  1. db.users.find({'last_name': 'Banker'})

suppose you know that the user’s last name starts with Ba

  1. db.users.find({'last_name': /^Ba/})

Querying specify ranges

  1. 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