Querying arrays
Arrays behave in a way that surprises people coming from SQL: matching an array field against a single value asks “does any element equal this?”. That one rule explains most array queries you will write.
Suppose:
{
name: "Denish",
skills: ["Node.js", "MongoDB", "Kafka"]
}
Find people with MongoDB:
db.users.find({
skills: "MongoDB"
})
MongoDB automatically matches an element inside the array.
You don’t need:
{
skills: {
$contains: "MongoDB"
}
}
That doesn’t exist.
Find documents containing any of these
db.users.find({
skills: {
$in: ["MongoDB", "Redis"]
}
})
Meaning:
User has MongoDB OR Redis.
Find documents containing all of these
db.users.find({
skills: {
$all: ["MongoDB", "Redis"]
}
})
Meaning:
User must have both.