Master two of the most powerful array query operators in MongoDB: $all and $elemMatch! This tutorial shows you exactly when and how to use them to find data in arrays and embedded documents.
What you will learn:
$all (Match All Values): Use $all when you need to find documents where an array field contains all the specified values, regardless of order. This is perfect for simple arrays (e.g., tags, sizes).
$elemMatch (Match Embedded Document): Use $elemMatch when you have an array of objects and you need to find documents where at least one object in that array matches all of your conditions.
Example ($all): Find products that have both "blue" and "medium" in their tags array: db.products.find({ tags: { $all: ["blue", "medium"] } })
Example ($elemMatch): Find students who have at least one grade that is both for "Math" AND has a score is greater than 90: db.students.find({ grades: { $elemMatch: { subject: "Math", score: { $gt: 90 } } } })
#MongoDB #Database #NoSQL #Programming #HowTo #TechTips #MongoDBTutorial