Daniel
Daniel

Reputation: 7172

Mongo aggregation, accessing a portion of an array

I have a mongo document like this

{
  '_id': .bson.
  'key': [ 'word1', 'word2', { 'key1': 'value1', 'key2': 'value2' } ] 
},

How do I use the mongo aggregation framework to make the document look like this:

{
  '_id': .bson.
  'key2': 'value2'
},

Thank you in advance!

-daniel

Upvotes: 0

Views: 62

Answers (1)

anhlc
anhlc

Reputation: 14459

db.collection.aggregate([ {$unwind: "$key"}, 
                          {$group : {
                                      "_id" : "$_id", 
                                      "key2": {$max: "$key.key2"}
                                    }
                          }])

Replace $max with $last if you are sure key.key2 is always present in the last element of key array.

Upvotes: 2

Related Questions