👐 Simple arrays
👐 Get all the Science Fiction Books
Can I get all books for the genre Science Fiction
?. Turns out it's quite simple:
- Atlas UI
- MongoDB Shell
[
{
$match: {
genres: 'Science Fiction'
}
}
]
db.books.aggregate([
{
$match: {
genres: 'Science Fiction'
}
}
])
Remember that will include any book that has any other genre as long as it has Science Fiction
in genres
.
👐 Find all the books that belong at least to both genres "Fiction" and "Science Fiction"
If you want to search for all books that have "Fiction" and "Science Fiction", in any order (and possibly other genres) use:
- Atlas UI
- MongoDB Shell
[
{$match: {
genres: {$all: ['Science Fiction', 'Fiction'] }
}
},
{$project: {
title: 1,
genres: 1
}}
]
db.books.aggregate([
{$match: {
genres: {$all: ['Science Fiction', 'Fiction'] }
}
},
{$project: {
title: 1,
genres: 1
}}
])
👐 Find books with either genre
- Atlas UI
- MongoDB Shell
[{
$match: {
genres: { $in: ['Science Fiction', 'Fiction'] }
}
}
]
db.books.aggregate([{
$match: {
genres: { $in: ['Science Fiction', 'Fiction'] }
}
}
]);
👐 Find all the books that belong only to the genres "Fiction" and "Science Fiction"
In this case, we want books that have both "Fiction" and "Science Fiction" in the genres array and nothing else. So we're looking for documents that contain a genres
array exactly as ['Fiction', 'Science Fiction']
. We're not looking for the individual genres that could be inside the array, instead we are comparing the whole array on each document.
- Atlas UI
- MongoDB Shell
[
{$match: {
genres: ['Fiction', 'Science Fiction']
}
},
{$project: {
title: 1,
genres: 1
}}
]
db.books.aggregate([
{$match: {
genres: ['Fiction', 'Science Fiction']
}
},
{$project: {
title: 1,
genres: 1
}}
])
Here we're comparing the whole array. Element order is important. With this comparison you'll get nothing in return:
- Atlas UI
- MongoDB Shell
[
{$match: {
genres: ['Science Fiction', 'Fiction']
}
},
{$project: {
title: 1,
genres: 1
}}
]
db.books.aggregate([
{$match: {
genres: ['Science Fiction', 'Fiction']
}
},
{$project: {
title: 1,
genres: 1
}}
])