Sling Academy
Home/MongoDB/Array data type in MongoDB: A practical guide (with examples)

Array data type in MongoDB: A practical guide (with examples)

Last updated: February 02, 2024

Introduction

MongoDB, as a NoSQL database, offers a flexible schema that allows for a variety of data types — one of the most powerful among them being the array data type. This article provides a practical guide to using arrays in MongoDB, suitable for developers of all levels who wish to harness the diversity MongoDB arrays provide.

The Fundamentals

In MongoDB, arrays are a data type that can hold multiple values, including other documents, arrays, and a mixture of different data types. This versatility makes arrays a cornerstone feature for modeling real-world data.

// Sample MongoDB document with an array field
{
    "_id": "1",
    "name": "John Doe",
    "interests": ["programming", "cycling", "travel"]
}

Creating Documents with Array Fields

To create a document with an array field, you can use the insert() or insertOne() method:

db.users.insert({
    name: "Jane Smith",
    interests: ["reading", "gardening", "gaming"]
});

This record will store Jane’s interests as an array.

Querying Documents with Array Fields

You can query documents by array elements using the find() method:

db.users.find({
    interests: "reading"
});

// Output
{
    "_id": "2",
    "name": "Jane Smith",
    "interests": ["reading", "gardening", "gaming"]
}

This query will retrieve documents where reading is an element of the interests array.

Updating Arrays

Updating an array can be achieved through various MongoDB array update operators:

  • $push: Adds an element to an array.
  • $addToSet: Adds an element to an array if it doesn’t exist already.
  • $pull: Removes an element from an array.
  • $pop: Removes the first or last element in an array.

Here’s how you can use $push to add a new interest:

db.users.updateOne(
    { name: "Jane Smith" },
    { $push: { interests: "photography" } }
);

After the update, Jane’s interests array will include “photography”.

Advanced Uses of Arrays in MongoDB

You can perform more complex operations, such as querying with criteria on arrays or updating specific elements in an array.

To project only the first element of an array:

db.users.find({}, { "interests": { $slice: 1 } });

Or update the second interest for Jane:

db.users.updateOne(
    { "name": "Jane Smith" },
    { $set: { "interests.1": "sketching" }}
);

// Updated output
{
    "_id": "2",
    "name": "Jane Smith",
    "interests": ["reading", "sketching", "gaming", "photography"]
}

Working with Complex Queries and Aggregations

MongoDB’s aggregation framework enables manipulating arrays with operators like $unwind and $group.

db.users.aggregate([
    { $unwind: "$interests" },
    { $group: {
        _id: "$interests",
        count: { $sum: 1 }
    } }
]);

// Example Output
[
    { "_id": "reading", "count": 20 },
    { "_id": "gardening", "count": 15 },
    // … more results
]

This would give us insights on how many users have each interest.

Conclusion

In this guide, we have explored various ways to work with arrays in MongoDB — from basic operations like creating and querying arrays, to more complex updates and aggregation operations. With this knowledge, you should be well-equipped to effectively utilize the array data type in your MongoDB-driven applications.

Next Article: Object data type in MongoDB: Tutorial & Examples

Previous Article: Understanding Min key and Max key in MongoDB (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)