coyotte508
coyotte508

Reputation: 9705

Possible to use value of an array's subdocument in an expression during mongodb aggregation?

Let's say I have this document:

{
  _id: 0,
  array: [{a: 120}, {a: 2452}]
}

And I want to obtain:

{
  _id: 0,
  array: [{a: 120}, {a: 2452}],
  a1x2: 240 // array[0].a * 2
}

Currently the simplest way I can think of to do this, in an aggregation, is:

db.collection.aggregate([{
  $match: {}
}, {
  $set: {aTmp: {$arrayElemAt: ["$array", 0]}}
}, {
  $project: {
    array: 1,
    a1x2: {$multiply: ["$aTmp.a", 2]},
    aTmp: 0
  }
}

Is there a way to do this without the intermediary step of setting aTmp? I don't know how to get a subdocument's value for a key when it's in the form of {$arrayElemAt: ["$array", 0]}.

I also tried using $array.0.a and $array[0].a, to no avail.

Upvotes: 1

Views: 94

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

You can use $let:

db.collection.aggregate([
  { $addFields: {
      a1x2: { $let: {
          vars: {
            aTmp: {$arrayElemAt: ["$array", 0]}
          },
          in: {$multiply: ["$$aTmp.a", 2]}
      }}
  } }
])

Upvotes: 2

Related Questions