GregH
GregH

Reputation: 12858

How do I specify/project a field in an embedded document within an array?

If I have a document in my MongoDB database like:

{"fld1": "value1",
 "fld2": "value2",
 "arr1": [{"arr1fld1": "arrval1", "arr1fld2": "arrval2"},
           "arr1fld1": "arrval3", "arr1fld2": "arrval4"}]
}

etc...is it possible to write a find if I want fld1 and "arr1fld2" but only of the first element of the array? Ideally my resulting document would look like:

{"fld1": "value1", "arr1fld2": "arrval2"}

I know I can use $slice to get the first array element...something like:

find({}, {"fld1": 1, "arr1": {$slice:1}})

But this returns:

{"fld1": "value1", "arr1": [{"arr1fld1": "arrval1", "arr1fld2": "arrval2"}]}

Upvotes: 1

Views: 125

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

According to description as mentioned into above question as a solution please try executing following aggregate query .

db.collection.aggregate(

        // Pipeline
        [
            // Stage 1
            {
                $project: {
                    array1: {
                        $arrayElemAt: ['$arr1', 0]
                    },
                    'fld1': 1
                }
            },

            // Stage 2
            {
                $project: {
                    arr1fld2: '$array1.arr1fld2',
                    fld1: 1,
                    _id: 0
                }
            }

        ]  
);

Upvotes: 0

jonhid
jonhid

Reputation: 2135

Using the Aggregation framework ...

You can get a projection with unwind

Then get the first element

db.fields.aggregate([
   {$project: { 
             fld1: 1,
             "arr1.arr1fld2": 1
       }
    },
    {$unwind : "$arr1" },
    {$group : {
           _id: "$_id",
           fld1: { $first: "$fld1"},
           arr1fld2: { $first: "$arr1.arr1fld2" }
         }
    }
])

Upvotes: 1

Related Questions