Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find length of the array mongodb

I have such this type of structure of my database. I want to find number of documents my "JAN" array contains. I am trying to do in different way but nothing works. That would be great if someone helps.

 {
            "_id" : ObjectId("5cd8609db20663a19e2c362c"),
            "2017" : {
                "JAN" : [
                    {
                        "SYMBOL" : "20MICRONS",
                        "SERIES" : "EQ",
                        "OPEN" : "33.4",
                        "HIGH" : "34.3",
                        "LOW" : "33",
                    },
                    {
                        "SYMBOL" : "3IINFOTECH",
                        "SERIES" : "EQ",
                        "OPEN" : "5.8",
                        "HIGH" : "5.8",
                        "LOW" : "5.55",
                    },
                    {
                        "SYMBOL" : "3MINDIA",
                        "SERIES" : "EQ",
                        "OPEN" : "11199.9",
                        "HIGH" : "11233",
                        "LOW" : "10861",
                    }
                ]
            }
        }
like image 948
Yash Choksi Avatar asked May 12 '19 18:05

Yash Choksi


1 Answers

You can use $size operator to find the length of the array

db.collection.aggregate([
  {
    "$project": {
      "totalJan": {
        "$size": "$2017.JAN"
      }
    }
  }
])

MongoPlayground

like image 112
Ashh Avatar answered Nov 16 '22 19:11

Ashh