Project an array with MongoDB

Question:

"customFields" : [
    {
        "index" : "1",
        "value" : "true",
        "label" : "isOffline",
        "dataType" : "check_box",
        "placeholder" : "cf_isoffline",
        "valueFormatted" : "true"
    },

    {
        "index" : "2",
        "value" : "false",
        "label" : "tenure_extended",
        "dataType" : "check_box",
        "placeholder" : "cf_tenure_extended",
        "valueFormatted" : "false"
    }
],

Answer:

db.subscription.aggregate([
  {$match:{"autoCollect" : false,"remainingBillingCycles" : -1,"customFields.value":"false", "customFields.label" : "isOffline"}},
  {$project: {first: { $arrayElemAt: [ "$customFields", 1 ] }}}
])

You can unwind the array and wind it u again after projecting. Something like this:

db.collectionName.aggregate([
{$unwind:'$authors'},
{$project:{_id:1,count:1,'author.id':'$authors.author.author','author.count':'$authors.count'}},
{$group:{_id:{_id:'$_id',count:'$count'},author:{$push:{id:'$author.id',count:'$author.count'}}}},
{$project:{_id:0,_id:'$_id._id',count:'$_id.count',author:1}}
])

the output for above will be:

{ 
    "_id" : "581c8c3df1325f68ffd23386", 
    "author" : [
        {
            "id" : "57f246b9e01e6c6f08e1d99a", 
            "count" : 13.0
        }, 
        {
            "id" : "5824382511f16d0f3fd5aaf2", 
            "count" : 1.0
        }
    ], 
    "count" : 14.0
}

I have been having the same problem and just now found a simple and elegant solution that has not been mentioned anywhere, so i thought I'd share it here:

You can iterate the array using $map and project each author. With the given structure, the aggregation should look somewhat like this

db.collectionName.aggregate([
  $project: {
    _id: 1,
    count:1,
    authors: {
      $map: {
        input: "$authors",
        as: "author",
        in: {
          id: "$$author.author.author",
          count: $$author.author.count
        }
      }
    } 
  }
])

Hope this helps anyone who is looking, like me :)