1

I have an inner array as the following:

[
    {'name': 'foo', 'size': 1},
    {'name': 'baz', 'size': 2},
    /* ... */

]

I'd like to update some outer field, total which is the sum of all sizes, without querying the array in advance.

I'm aware of the aggregate paradigm but I'm not sure how to apply it here, if needed at all.

Thanks

IsaacLevon
  • 2,260
  • 4
  • 41
  • 83

1 Answers1

1

You can use aggregation pipeline with $out to write to a new or existing collection

db.t61.aggregate([
    {$addFields : {total : {$sum : "$data.size"}}},
    {$out : "t61"}
])

sample collection and aggregation

> db.t61.find()
{ "_id" : ObjectId("5c44d5709d56bf65be5ab2e2"), "data" : [ { "name" : "foo", "size" : 1 }, { "name" : "baz", "size" : 2 } ] }
> db.t61.aggregate([{$addFields : {total : {$sum : "$data.size"}}},{$out : "t61"}])
> db.t61.find()
{ "_id" : ObjectId("5c44d5709d56bf65be5ab2e2"), "data" : [ { "name" : "foo", "size" : 1 }, { "name" : "baz", "size" : 2 } ], "total" : 3 }
>
Saravana
  • 12,647
  • 2
  • 39
  • 57