Sikau

MongoDB · Day 7 · about 30 min

Arrays of sub-documents

$elemMatch, positional updates and array operators.

One element must match it all

"Orders with a Momo line of quantity 2 or more" — both conditions must hold for the *same* item. Plain dot notation can match different items for each condition; $elemMatch keeps them together.

$elemMatch, $size, $all

printjson(db.orders.find({ "items.dish": "Momo", "items.qty": { $gte: 2 } }, { _id: 0, customer: 1 }).toArray());

printjson(db.orders.find({ items: { $elemMatch: { dish: "Masala tea", qty: { $gte: 2 } } } }, { _id: 0, customer: 1 }).toArray());

printjson(db.orders.find({ items: { $size: 1 } }, { _id: 0, customer: 1, status: 1 }).toArray());

printjson(db.dishes.find({ tags: { $all: ["fried", "sweet"] } }, { _id: 0, name: 1 }).toArray());

db.orders.updateOne({ customer: "c2" }, { $push: { items: { dish: "Masala tea", qty: 1, price: 50 } } });
db.orders.updateOne({ customer: "c2" }, { $pull: { items: { dish: "Thukpa" } } });
printjson(db.orders.findOne({ customer: "c2" }, { _id: 0, items: 1 }));

The rest of this lesson

  • Updating one array elementexplain
  • Array operators at a glanceexplain
  • Match?predict
  • Same element or not?predict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB