MongoDB multidimensional array projection?

For MongoDB multidimensional array projection, you need to use the aggregate framework. This allows you to access and project specific elements from nested arrays using operators like $unwind, $project, $skip, and $limit.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $project: { _id: 0, arrayField: 1 } },
    { $unwind: "$arrayField" },
    { $skip: index },
    { $limit: 1 }
]);

Sample Data

db.multiDimensionalArrayProjection.insertOne({
    "StudentFirstName": "Chris",
    "StudentMarks": [ [98, 99], [56, 79] ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cc6b75a9cb58ca2b005e66c")
}

Let's view our sample document ?

db.multiDimensionalArrayProjection.find().pretty();
{
    "_id": ObjectId("5cc6b75a9cb58ca2b005e66c"),
    "StudentFirstName": "Chris",
    "StudentMarks": [
        [
            98,
            99
        ],
        [
            56,
            79
        ]
    ]
}

Example: Project Specific Element from Multidimensional Array

To extract the second element (99) from the first sub-array [98, 99] ?

db.multiDimensionalArrayProjection.aggregate([
    { $unwind: "$StudentMarks" },
    { $limit: 1 },
    { $project: { _id: 0, StudentMarks: 1 } },
    { $unwind: "$StudentMarks" },
    { $skip: 1 },
    { $limit: 1 }
]);
{ "StudentMarks": 99 }

How It Works

  • $unwind: "$StudentMarks" − Flattens the outer array into separate documents
  • $limit: 1 − Takes only the first sub-array [98, 99]
  • $project − Removes _id and keeps only StudentMarks
  • $unwind: "$StudentMarks" − Flattens the sub-array elements
  • $skip: 1 − Skips the first element (98)
  • $limit: 1 − Returns only the second element (99)

Conclusion

Use MongoDB's aggregation pipeline with $unwind operations to project specific elements from multidimensional arrays. Combine $skip and $limit to target exact positions within nested array structures.

Updated on: 2026-03-15T00:54:09+05:30

708 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements