Skip to content

Latest commit

 

History

History
137 lines (105 loc) · 1.87 KB

80-array-sizes.mdx

File metadata and controls

137 lines (105 loc) · 1.87 KB

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

🦸 Size of an Array

What if we want to know how many aliases an author has? To do that, we can use $size, adding the array field that we're interested in:

[
  { $project: {
      name: 1,
      bookCount: {$size: "$books"}
    }
  },
]
```js db.authors.aggregate([ { $project: { name: 1, bookCount: {$size: "$books"} } }, ]) ```

👐 Who wrote the most books? (We can sort using { $sort: {"bookCount": -1}}.)

Answer
[
  {
    $project: {
        name: 1,
        bookCount: {$size: "$books"}
    }
  },
  { $sort: {"bookCount": -1} },
  { $limit: 1 }
]
let addNumberBooks = {
  $project: {
      name: 1,
      bookCount: {$size: "$books"}
  }
}

let orderByNumberOfBooksDesc = { $sort: {"bookCount": -1} }

let getOne = { $limit: 1 }

db.authors.aggregate([
  addNumberBooks,
  orderByNumberOfBooksDesc,
  getOne,
])

👐 Find books with exactly three genres (we can $match using { {"bookCount": -1}}).

Answer
[
  { 
      $match: { 
      genres: {$size: 3 } 
      } 
  },
  {$project: {
      title: 1,
      genres: 1
  }}
]
db.books.aggregate([
  { 
      $match: { 
      genres: {$size: 3 } 
      } 
  },
  {$project: {
      title: 1,
      genres: 1
  }}
])