👐 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:
- Atlas UI
- MongoDB Shell
Remember to select the authors
collection in the UI.
[
{ $limit: 1 }
]
db.authors.aggregate([
{ $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:
- Atlas UI
- MongoDB Shell
[
{$match: {books: "0002005018"}}
]
db.authors.aggregate([
{$match: {books: "0002005018"}}
])
👐 Get the book's author name for ISBN 0395623650
:
Answer
- Atlas UI
- MongoDB Shell
[
{ $match: {books: "0395623650"} }
]
> name: 'Juan Ramón Jiménez',
db.authors.aggregate([
{ $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:
- Atlas UI
- MongoDB Shell
[
{ $project: {
name: 1,
bookCount: {$size: "$books"}
}
},
]
db.authors.aggregate([
{ $project: {
name: 1,
bookCount: {$size: "$books"}
}
},
])