import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';
Can I get all books for the genre Science Fiction
? Turns out it's quite simple:
[
{
$match: {
genres: 'Science Fiction'
}
}
]
Remember that will include any book that has any other genre as long as it has Science Fiction
in genres
.
If you want to search for all books that have "Fiction" and "Science Fiction," in any order (and possibly other genres), use:
[
{$match: {
genres: {$all: ['Science Fiction', 'Fiction'] }
}
},
{$project: {
title: 1,
genres: 1
}}
]
[{
$match: {
genres: { $in: ['Science Fiction', '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.
[
{$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:
[
{$match: {
genres: ['Science Fiction', 'Fiction']
}
},
{$project: {
title: 1,
genres: 1
}}
]