How to find length of embedded nested array in mongodb?

人走茶凉 提交于 2020-12-13 11:14:31

问题


How to find length of embedded nested array in mongodb? For example, I have the below collection in my mongoDB. The loc field contains coordinates field which is an array and again it contains another array which is in 0th index. How can I find length of loc.corrdinates[0] ? I tried to do this with using aggregation pipeline but it gives syntax error:

db.atolldata.aggregate([
                        {$project:{_id:0,
                                   fileName:1,
                         sizeOfArray:{$size:"$loc.coordinates[0]"}}}]); 

.

Here is my collection

db.mydb.findOne();

{
    "_id" : ObjectId("54ccb36fe4b0ff85abfee006"),
    "_class" : "com.inn.signaleye.model.AtollData",
    "rsrp" : "-124",
    "index" : 1,
    "rgb" : [
        192,
        157,
        0
    ],
    "loc" : {
        "type" : "Polygon",
        "coordinates" : [
            [
                [
                    91.5254213240325,
                    26.225096
                ],
                [
                    91.5254099392226,
                    26.225999
                ],
                [
                    91.52591034644685,
                    26.226004
                ],
                [
                    91.52592172739666,
                    26.225101
                ],
                [
                    91.5254213240325,
                    26.225096
                ]
            ]
        ]
    },
    "fileName" : "RSRP_ZOne46N_20m_SCFT.shp"
}

回答1:


Make use of the $unwind stage, to flatten the coordinates array, and then find the size in the $project stage.

db.atolldata.aggregate([
{$unwind:"$loc.coordinates"},
{$project:{"_id":0,"fileName":1,
           "sizeOfArray":{$size:"$loc.coordinates"}}}
])


来源:https://stackoverflow.com/questions/28253590/how-to-find-length-of-embedded-nested-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!