6

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.

3 Answers 3

8

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"
                }
            }
        }
    }
])
Sign up to request clarification or add additional context in comments.

1 Comment

How do you add all the items by a specific key on the item/object and not just the first?
3

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.

Comments

0

Another alternative I've found is using first and $getField which is new since Version 5.0

db.collection.aggregate([
  {
    $addFields: { 
      text1: {
        $getField: {
          field: 'text',
          input: { $first: '$arr' }
        }
      }
    }
  }
]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.