跳到主要内容

👐 Simple arrays

👐 Get all the Science Fiction Books

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.

👐 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:

[
{$match: {
genres: {$all: ['Science Fiction', 'Fiction'] }
}
},
{$project: {
title: 1,
genres: 1
}}
]

👐 Find books with either genre

[{ 
$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.

[
{$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
}}
]