Not valid for storage

Viewed 219

I get the error:

The dollar ($) prefixed field '$size' in 'analytics.visits.amounts..$size' is not valid for storage.

return Manager.updateMany({},
        {
            $push: {
                "analytics.visits.amounts": {$size: "$ips"},
                "analytics.visits.dates": new Date()
            }

        }
).exec()

What I try to do is I have an array called ips and I have another array amounts and I try to push the size of ips into the amounts array

The structure of a single document is:

{
    offices: [{
       ips: []
    }],
    analytics: {
        visits: {
            amounts: [],
            dates: []
        }
    }
}
1 Answers

The normal update syntax can not use document variable values, meaning the $ips is what's throwing you the error.

For Mongo v4.2+ they introduced pipelined updates which allows you to use document values in an update, like so:

db.collection.updateMany(
{},
[
  {
    $set: {
      "analytics.visits.amounts": {
        $concatArrays: [
          "$analytics.visits.amounts",
          [
            {
              $reduce: {
                input: "$offices",
                initialValue: 0,
                in: {
                  $sum: [
                    {
                      $size: "$$this.ips"
                    },
                    "$$value"
                  ]
                }
              }
            }
          ]
        ]
      },
      "analytics.visits.dates": {
        $concatArrays: [
          "$analytics.visits.dates",
          [
            new Date()
          ]
        ]
      },
      
    }
  }
])

Mongo Playground

If you're using an older Mongo version then you will have to read the documents into memory in order to fetch the ips values to use in the update.

Related