Skip to main content

👐 Simple Array Queries

Find data in arrays

A JSON array can contain scalar values or objects. In our data, authors have an array of the books they've authored (their ISBNs as Strings). Let's get one author:

Remember to select the authors collection in the UI.

[
{ $limit: 1 }
]

👐 Run this aggregation to get one author.

I got this one. (It can change depending on the data source you imported.)

{
_id: ObjectId("64cc2db4830ba29148da4c3b"),
name: 'Richard Bruce Wright',
sanitizedName: 'richardbrucewright',
books: [
'0002005018'
],
aliases: [
'Wright, Richard Bruce'
]
}

Can I get all authors for book 0002005018? For that, I want all authors that have 0002005018 inside the books array. Turns out it's quite simple:

[
{$match: {books: "0002005018"}}
]

👐 Get the book's author name for ISBN 0395623650:

Answer
[
{ $match: {books: "0395623650"} }
]
>   name: 'Juan Ramón Jiménez',

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"}
}
},
]

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

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