1

I need to find size of an array in a document.

Example:
{
  "_id" : "2",
  "coord" : [1,2,3,4,5]
}

I need size of coord.

How do i find it? Can anybody help me on this?

3 Answers 3

1

I suggest to use the aggregation framework.


    db.temps.aggregate([{$unwind:"$coord"},{$group:{_id:"$_id", coord_length:{$sum:1}}}])

If you have multiple documents with different coordinates, it will show the length of that array. You could add the $match operator for finding specific documents.

Sign up to request clarification or add additional context in comments.

Comments

0

say ex is a variable referenced to the example item mentioned above

ex = { "_id" : "2", "coord" : [1,2,3,4,5] }

you can get the length of "coord" by

ex["coord"].length

Comments

0

You can use the $size aggregation operator for that:

db.test.aggregate({$project: {size: {$size: '$coord'}}})

Output

{ "_id": "2", "size": 5 }

Note that the $size operator was added in version 2.6.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.