Question

I've checked out an older question that is related with my embedded paging situation. Although the embedded paging with slicing works fine, the total pages solution is still missing, and i wonder whether it's possible to get the total size of the comments on the server side.

Is there a way to query or count the size of the embedded array on the server without having to fetch the whole document to my app and count it manually ?

I dont mind making 2 queries for this, 1 for paging the comment, 1 for getting the total of the comments. If i can do this in one query, that'll be amazing though.

By the way, i am using the java driver and spring-data mongodb.

Please share your thoughts. Thanks !

Was it helpful?

Solution

Best/fastest way to get total count of embedded documents is create an additional field and recalculate count after each update/insert. Document will be like this

{
  _id: 1,
  comments: [],
  commentsCount: 5
}

Then you can simply include commentsCount field when do slice:

//this query will include only 10 comments _id and comments count of root document
db.articles.find({}, {comments:{$slice: [20, 10]}, _id:1, commentsCount: 1}) 

And actually there is no other way to calculate total count of embedded documents (i am not talking about m/r, because it is slow for real time requests)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top