MongoDB Tutorial 0/120 lessons ~6 min read Lesson 19
Arrays in MongoDB
Arrays are first-class citizens in MongoDB.
Course progress0%
Focus
6 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
Arrays are first-class citizens in MongoDB. You can store them, query them, project specific elements, and atomically push/pull/update items. Most NoSQL databases treat arrays as opaque blobs — MongoDB lets you reach inside them with surgical precision.
Understanding the topic
Powerful array operators:
$push/$pull— atomic add/remove.$addToSet— push only if absent (set semantics).$elemMatch— match an array element by multiple criteria.$size— match by array length.arrayFilters— update specific matching elements.
Syntax reference
js
// Tag a postdb.posts.updateOne({ _id: 1 }, { $addToSet: { tags: "mongodb" } });// Find users with at least one admin roledb.users.find({ roles: { $elemMatch: { $eq: "admin" } } });// Increment one variant's stockdb.products.updateOne({ _id: 1, "variants.color": "blue" },{ $inc: { "variants.$.stock": 5 } });
Real-world use
Tags on a blog post, line items on an order, attendees on an event — all idiomatic array use cases.
Best practices
- Cap arrays at ~hundreds of elements.
- Use multikey indexes for queried array fields.
Common mistakes
- Storing millions of items in one array — use a separate collection.
Ready to mark this lesson complete?Track your journey across the entire course.