mongodb - Can we set a new key equal to an array element in $project statement? -


in mongo, can this:

db.hi.aggregate({$project: {new_val: '$tags.first'}}) 

however, doesn't work:

db.hi.aggregate({$project: {new_val: '$my_array.0'}}) 

does mean aggregation doesn't support array in way? there alternative?

presently aggregation framework doesn't yet support this, there's in progress jira ticket here , there.

an alternative first $unwind array, $group deconstructed array documents _id key. in grouped documents, retrieve first array element $first group accumulator operator:

db.hi.aggregate([     {          "$unwind": "$my_array"      },     {          "$group": {             "_id": "$_id",             "new_val": { "$first": "$my_array" }         }     } ]) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -