skip to Main Content

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

2

Answers


  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"}}}}])
    
    Login or Signup to reply.
  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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search