Page Content

Tutorials

What is the Array Length Operator in MongoDB?

Array Length Operator in MongoDB

Data stored in arrays within documents can be processed and transformed using a set of robust array expression operators that MongoDB offers within the aggregation pipeline. These operators, which are frequently used in stages like $project and $group, enable complex data manipulation and analysis.

Array Length Operator in MongoDB
Array Length Operator in MongoDB

Let’s use a collection named courses with the following sample data:

db.courses.insertMany([
    {
        "_id": 1,
        "title": "Database Fundamentals",
        "instructor": "Dr. Smith",
        "students": ["Alice", "Bob", "Charlie"],
        "modules": [
            { "name": "Introduction to SQL", "durationMinutes": 60 },
            { "name": "NoSQL Concepts", "durationMinutes": 90 }
        ],
        "tags": ["database", "sql", "nosql", "beginners"]
    },
    {
        "_id": 2,
        "title": "Advanced JavaScript",
        "instructor": "Prof. Johnson",
        "students": ["David", "Eve"],
        "modules": [
            { "name": "ES6 Features", "durationMinutes": 120 },
            { "name": "Asynchronous JS", "durationMinutes": 150 },
            { "name": "Frontend Frameworks", "durationMinutes": 180 }
        ],
        "tags": ["javascript", "web", "advanced"]
    },
    {
        "_id": 3,
        "title": "Machine Learning Basics",
        "instructor": "Dr. Smith",
        "students": [],
        "modules": [
            { "name": "ML Algorithms", "durationMinutes": 100 }
        ],
        "tags": ["ai", "machine learning", "data science"]
    },
    {
        "_id": 4,
        "title": "Python for Data Analysis",
        "instructor": "Prof. Lee",
        "students": ["Frank", "Grace", "Heidi", "Ivan"],
        "modules": [
            { "name": "Pandas Basics", "durationMinutes": 90 },
            { "name": "Numpy Operations", "durationMinutes": 75 },
            { "name": "Data Visualization", "durationMinutes": 110 }
        ],
        "tags": ["python", "data science"]
    },
    {
        "_id": 5,
        "title": "Cloud Computing",
        "instructor": "Ms. Miller",
        "students": null, // Example of a non-array field
        "modules": [],
        "tags": ["cloud", "aws", "azure"]
    }
]);

The array expression operators you asked about are explained here:

$isArray Operator

The $isArray operator returns a boolean indicating whether the specified expression is an array.

Syntax:

{ $isArray: <expression> }

Code Examples:

Find courses where the students field is actually an array, and project this information:

db.courses.aggregate([
    {
        $project: {
            _id: 0,
            title: 1,
            students: 1,
            isStudentsArray: { $isArray: "$students" }
        }
    }
]).pretty();

Match documents where students is an array (excluding course 5):

db.courses.aggregate([
    {
        $match: {
            students: { $isArray: true } // Or { $expr: { $isArray: "$students" } }
        }
    },
    {
        $project: {
            _id: 0,
            title: 1,
            students: 1
        }
    }
]).pretty();

$size Operator

The number of elements in an array can be found with the $size operator. It merely returns a value that indicates the number of elements in the designated array when used in a $project stage.

Syntax:

{ $size: <array expression> }

Code Example:

Project the title and the number of students in each course:

db.courses.aggregate([
    {
        $project: {
            _id: 0,
            title: 1,
            numberOfStudents: { $size: "$students" }
        }
    }
]).pretty();

Find courses with exactly 3 students:

db.courses.aggregate([
    {
        $match: {
            students: { $size: 3 }
        }
    },
    {
        $project: {
            _id: 0,
            title: 1,
            students: 1
        }
    }
]).pretty();

$arrayElemAt Operator

The $arrayElemAt operator selects a single element at a slot in an array. The first member of MongoDB arrays is index 0. Access the last element of the array using negative indices, such as -1.

Syntax:

{ $arrayElemAt: [ <array expression>, <idx> ] }

Code example:

Project the title and the first student enrolled in each course:

db.courses.aggregate([
    {
        $project: {
            _id: 0,
            title: 1,
            firstStudent: { $arrayElemAt: ["$students", 0] }
        }
    }
]).pretty();

Project the title and the last tag for each course:

db.courses.aggregate([
    {
        $project: {
            _id: 0,
            title: 1,
            lastTag: { $arrayElemAt: ["$tags", -1] } // -1 gets the last element
        }
    }
]).pretty();

$concatArrays Operator

There is no direct information on a $concatArrays operator. However, for concatenating strings, the $concat string expression function is mentioned. A comparable array operator might be included in more recent MongoDB versions that aren’t completely covered or it could be accomplished using different aggregation techniques.

Syntax:

{ $concatArrays: [ <array1>, <array2>, ... ] }

Code example:

Combine the students array with a new array of assistants for “Database Fundamentals”:

db.courses.aggregate([
    {
        $match: { "_id": 1 }
    },
    {
        $project: {
            _id: 0,
            title: 1,
            allParticipants: { $concatArrays: ["$students", ["Assistant A", "Assistant B"]] }
        }
    }
]).pretty();

Create a combined keywords array from tags and genre (if genre were an array in another collection, here we’ll just include a constant):

db.courses.aggregate([
    {
        $match: { "_id": 2 } // Advanced JavaScript
    },
    {
        $project: {
            _id: 0,
            title: 1,
            allKeywords: { $concatArrays: ["$tags", ["programming", "web development"]] }
        }
    }
]).pretty();

$reverseArray Operator

The $reverseArray operator returns an array with the elements in reverse order.

Syntax:

{ $reverseArray: <array expression> }

Code example:

Project the title and the tags array in reverse order:

db.courses.aggregate([
    {
        $project: {
            _id: 0,
            title: 1,
            originalTags: "$tags",
            reversedTags: { $reverseArray: "$tags" }
        }
    }
]).pretty();

Reverse the order of modules and project only the module names for “Advanced JavaScript”:

db.courses.aggregate([
    {
        $match: { "_id": 2 }
    },
    {
        $project: {
            _id: 0,
            title: 1,
            reversedModuleNames: {
                $map: { // Using $map to extract only names after reversal
                    input: { $reverseArray: "$modules" },
                    as: "module",
                    in: "$$module.name"
                }
            }
        }
    }
]).pretty();

In conclusion

The references given provide thorough explanations of the $size and $arrayElemAt array expression operators, including how to use them and significant restrictions on $size. The provided material lacks information on $isArray, $concatArrays, and $reverseArray. These operators enable strong transformations and calculations on array data and are essential to MongoDB’s aggregation system.

Index