MongoDB multidimensional array projection?


For MongoDB multidimensional array projection, you need to use aggregate framework. Let us first create a collection with documents. Here, we have multidimensional array for Student marks −

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

Following is the query to display all documents from a collection with the help of find() method −

> db.multiDimensionalArrayProjection.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc6b75a9cb58ca2b005e66c"),
   "StudentFirstName" : "Chris",
   "StudentMarks" : [
      [
         98,
         99
      ],
      [
         56,
         79
      ]
   ]
}

Following is the query for MongoDB multidimensional array projection −

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

This will produce the following output −

{ "StudentMarks" : 99 }

Updated on: 30-Jul-2019

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements