How can I get the length of a MongoDb array field? [SOLVED]

I need to get the length of an array stored as a field in a Mongo document. I looked at use of the $size operator in the Mongo docs, but it is not clear to me how I can get Mongo to return the $size value.

For example, let’s say I have:

MyCollection = new Mongo.Collection('mongoCollection');
MyCollection.insert({myArray: ["item 1", "item 2"]});

How can I get the length value of MyCollection.myArray?

$size is only available to the aggregation framework, which, you can only use on the server side through direct mongo access or one of the aggregation packages.

Another approach would be to query for the array and manually get the length as in

MyCollection = new Mongo.Collection('mongoCollection');
var id = MyCollection.insert({myArray: ["item 1", "item 2"]});
MyCollection.findOne(id).myArray.length;
1 Like

I’d probably handle that in the insert’s callback just in case the insert errors…

That solved it - thanks! (And so obvious now that I see it - I think I was too focused on Mongo and not just a basic length check.)

1 Like