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

Updated: February 2, 2024 By: Guest Contributor Post a comment

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.