Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add field of array element in MongoDB aggregation

I have a collection of documents containing an array of objects:

db.collection.insert({
    arr: [
      { id: 1, text: 'foo' },
      { id: 2, text: 'bar' },
    ]
});

Is there a way to extract/project/add a field of one element in that array? For example, the text field of the first element of the array. I've tried various variations of $addFields in MongoPlayground,

db.collection.aggregate([
  {
      $addFields: { text1: '$arr.text' }
  }
]);

but nothing produced just one text field. At best, I got both, with the syntax above, but I want only one field, in order to use $type on it, because it appears $type can't inspect array elements.

like image 941
Dan Dascalescu Avatar asked Jun 13 '19 04:06

Dan Dascalescu


2 Answers

You can use $let with $arrayElemAt to define temporary variable and then reference it to get text field:

db.collection.aggregate([
    {
        $addFields: {
            text1: {
                $let: {
                    vars: {
                        first: {
                            $arrayElemAt: [ "$arr", 0 ]
                        }
                    },
                    in: "$$first.text"
                }
            }
        }
    }
])
like image 159
mickl Avatar answered Nov 15 '22 04:11

mickl


One way to extract a field of an array element is to project the first element using $arrayElemAt in a $project stage, then to access the desired field, e.g. text, in a second $project stage:

db.collection.aggregate([
  {
    $project: {
      elem1: {
        $arrayElemAt: ["$arr", 0]
      }
    }
  },
  {
    $project: {
      text1: "$elem1.text"
    }
  }
])

Mongo Playground.

like image 45
Dan Dascalescu Avatar answered Nov 15 '22 03:11

Dan Dascalescu