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

Time:05-17

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
}]

CodePudding user response:

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"}}}}])

CodePudding user response:

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.

  • Related