2

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
  • BatScream's answer is good, but are you actually trying to get the length of coordinates in a single document, or in all documents? If the former, it may be easier to just get that document by ID and compute its length in your application. Commented Feb 2, 2015 at 17:40

2 Answers 2

3

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"}}}
])
Sign up to request clarification or add additional context in comments.

Comments

0

You might want to create a field with the size of the array to work with it:

{$set : {arraySize: {$size: {$arrayElemAt : ['$loc.coordinates', 0]}}}}

Remember all documents have to include the loc field or the aggregation will fail (so you have to filter these documents first with $match).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.