Skip to content

Arrays & Nested Documents

Querying Arrays

Equality, contains, and the difference between matching a value and matching a whole array.

IntermediateAbout 5 minutes

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" })
Contains. One value, anywhere in the array.
{ 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" })
Exact array. Order and length both matter.

{ 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?

Think about it first.