1

Im writing a simple query to return user content/posts. I also need to show the number of comments each post has.

My document structure looks like this

posts {
  content: string,
  comments: [array of object ids]
  ...
}

I know how to get the size of the comments array using aggregate function. I also know that i could add a "commentsNr" property and increment it using post save hooks. And...i know i can execute the query....return the posts array, and use the post.comments.length property, but i don't want to return the entire comments array just to count it.

All my queries are very simple, and i don't want to make them any more complicated than necessary. So, im looking for a way to return the length of the comments array as a new field, i.e use projection or something like that.

Is there a way to use simple find query to get the length of the document array, without returning the array itself ?

Community
  • 1
  • 1
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42
  • Why not using aggregation and then $size ? – meshkati Jul 30 '17 at 17:27
  • I think that invoking aggregation framework just to return something so basic as array length property seems like an overkill. Unnecessary level of complexity and also a bit reduced performance. If there is a way to get the length of an array in a simple find query, then i would prefer that. i.e Posts.find({_id: some id}, {commentsNr: "$comments.length" } ) or Posts.find({_id: some id}, {commentsNr: {$size: 'comments'} } ) – Rainer Plumer Jul 30 '17 at 17:43

1 Answers1

0

I see your intention but I'm sorry... It is not possible to use $size in a projection outside the aggregation framework. Go for the aggregation option, though, without feeling bad about it! This framework is so amazing that you will want to use it at some point anyway...

Mistalis
  • 17,793
  • 13
  • 73
  • 97
dnickless
  • 10,733
  • 1
  • 19
  • 34