0

I have a data similar to the below in my mongo DB. Obviously the length of array1 is two and I am looking on a way to count the length of such array with mongo db script. Thanks

{
        "_id" : ObjectId("65465465465465465468"),
        "header" : {
                "test" : "test",
        },
        "value" : 11.763548134011048,
        "array1" : [
                {
                        "q" : {
                                "value" : 250
                        }
                },
                {
                        "q" : {
                                "value" : 30,
                        }
                }
        ],
        "array2" : [ ]
}
Sam
  • 167
  • 3
  • 14

1 Answers1

1

You can use the $size aggregation operator.

Given the document you showed in your OP, the following command ...

db.collection.aggregate(
   [
      {
         $project: {          
            sizeOfArray1: { $size: "$array1" }
         }
      }
   ]
)

... will return:

{
    "_id" : ObjectId("65465465465465465468"),
    "sizeOfArray1" : 2
}

This approach is valid for all versions of Mongo >= 2.6.

Update: in response to this comment ...

If I have more nested objects until I reach to my array I can use they same code and I just change the name of the field to the item that I am interested in?

You address any document attribute using path notation with a . to denote each 'level'. So, if your document looked like this:

{
        "_id" : ObjectId("65465465465465465468"),
        "header" : {
                "test" : "test",
                "array" : [1, 2, 3]
        },
        "value" : 11.763548134011048,
        "array1" : [
                {
                        "q" : {
                                "value" : 250
                        }
                },
                {
                        "q" : {
                                "value" : 30,
                        }
                }
        ],
        "array2" : [ ]
}

... then the following command would return the count of the array field inside the header nested sub document:

db.collection.aggregate(
   [
      {
         $project: {          
            sizeOfHeaderArray: { $size: "$header.array" }
         }
      }
   ]
)

So, perhaps you can now see that you would address the array field inside the header nested sub document using header.array.

Hope that helps.

glytching
  • 44,936
  • 9
  • 114
  • 120
  • Thanks glitch. just it looks not very much intuitive. If I have more nested objects until I reach to my array I can use they same code and I just change the name of the field to the item that I am interested in? – Sam Oct 25 '17 at 19:36