Arrays & Nested Documents
Querying Arrays
Equality, contains, and the difference between matching a value and matching a whole array.
Rahul's skills is ['Node.js', 'MongoDB'] — an array of scalars. Three different questions: contains this value, equals this exact array, this index.
db.users.find({ skills: "MongoDB" }){ name: "Rahul", skills: ["Node.js", "MongoDB"] }db.users.find({ skills: ["Node.js", "MongoDB"] })
// misses if skills is ["MongoDB", "Node.js"] or has a third element
db.users.find({ "skills.0": "Node.js" }){ skills: "MongoDB" } is contains. { skills: ["Node.js", "MongoDB"] } is equals. $in on an array field means 'the array shares at least one value with this list' — { skills: { $in: ["Redis", "MongoDB"] } } still matches Rahul. $size matches length: { skills: { $size: 2 } }.
Interview question
How do you find documents where an array contains a value, versus equals a list?
Contains: { skills: "MongoDB" }. Exact list: { skills: ["Node.js", "MongoDB"] } — order and length must match. $in tests overlap with a list of candidates.