Solution & Challenge: Insert and Find Operations · MongoDB
Ch 2 · MongoDB CRUD Operations — card 4 of 8.
Compare your answer with the worked solution, which inserts five products in one call, finds those over 50 and counts the electronics. The challenge builds a fuller inventory: at least ten products, searches that combine a price range and a category with $and, sorting by price to find the most expensive item, and a projection that returns only names and prices.
await col.insertMany([
{ name: "Laptop", price: 999, category: "electronics" },
{ name: "Book", price: 15, category: "books" },
{ name: "Phone", price: 699, category: "electronics" },
{ name: "Pen", price: 2, category: "office" },
{ name: "Tablet", price: 449, category: "electronics" }
]);
const expensive = await col.find({ price: { $gt: 50 } }).toArray();
console.log("Expensive:", expensive.length);
const elecCount = await col.countDocuments({ category: "electronics" });
console.log("Electronics:", elecCount);- Insert at least 10 products
- Search with $and combining price range and category
- Sort by price descending to find most expensive
- Use projection to return only name and price