Prakki
Prakki

Reputation: 159

Find size of an array in a document

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?

Upvotes: 1

Views: 61

Answers (3)

JohnnyHK
JohnnyHK

Reputation: 312115

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.

Upvotes: 0

Kevin
Kevin

Reputation: 516

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.

Upvotes: 1

Ashoka Lella
Ashoka Lella

Reputation: 6729

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

Upvotes: 0

Related Questions