Skip to content

Latest commit

 

History

History
182 lines (148 loc) · 3.17 KB

20-simple-match-array.mdx

File metadata and controls

182 lines (148 loc) · 3.17 KB

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

👐 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' 
    } 
  }
]
```js 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:

[
  {$match: { 
      genres: {$all: ['Science Fiction', 'Fiction'] } 
      } 
  },
  {$project: {
      title: 1,
      genres: 1
  }}
]
```js db.books.aggregate([ {$match: { genres: {$all: ['Science Fiction', 'Fiction'] } } }, {$project: { title: 1, genres: 1 }} ]) ```

👐 Find books with either genre

[{ 
    $match: {
      genres: { $in: ['Science Fiction', 'Fiction'] }
    }
  }
]
```js 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.

[
  {$match: { 
      genres: ['Fiction', 'Science Fiction'] 
    } 
  },
  {$project: {
    title: 1,
    genres: 1
  }}
]
```js 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:

[
  {$match: { 
      genres: ['Science Fiction', 'Fiction'] 
    } 
  },
  {$project: {
    title: 1,
    genres: 1
  }}
]
```js db.books.aggregate([ {$match: { genres: ['Science Fiction', 'Fiction'] } }, {$project: { title: 1, genres: 1 }} ]) ```