'Add field to mongo that contain the value of the document's length

Sample document

[{
  "_id": "1111",
  "name": "Dani"
},
{
  "_id": "2222",
  "name": "Guya",
  "address": "Arlozorov",
  "city": "Tel Aviv"
}]

Expected output, i want to add the length field

[{
  "_id": "1111",
  "name": "Dani",
  "length": 2
},
{
  "_id": "2222",
  "name": "Guya",
  "address": "Arlozorov",
  "city": "Tel Aviv",
  "length": 4
}]



Solution 1:[1]

Query

  • $$ROOT is the document (system variable)
  • convert it to an array
  • take the array length and $set

Playmongo

aggregate(
[{"$set": {"length": {"$size": {"$objectToArray": "$$ROOT"}}}}])

Solution 2:[2]

There's a fair amount of ambiguity in your description of "length". For example, if there is an array, does that count as one, or should the array contents be counted too? Same for embedded/nested fields documents, etc. And should the ever present "_id" field be counted?

Anyway, given your example documents and desired output, here's one way you could update each document with your "length" field.

db.collection.update({},
[
  {
    "$set": {
      "length": {
        "$subtract": [
          {
            "$size": {
              "$objectToArray": "$$ROOT"
            }
          },
          1
        ]
      }
    }
  }
],
{
  "multi": true
})

Try it on mongoplayground.net.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Takis
Solution 2 rickhg12hs