Reputation: 159
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
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
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
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