我检查了一个与我的嵌入式分页情况相关的旧问题。尽管带有切片的嵌入式分页工作正常,但仍然缺少总页面解决方案,我想知道是否有可能在服务器端获得评论的总大小。
有没有办法查询或计算服务器上嵌入数组的大小,而不必将整个文档提取到我的应用程序并手动计算它?
我不介意为此进行 2 次查询,1 次用于分页评论,1 次用于获取评论总数。如果我可以在一个查询中做到这一点,那将是惊人的。
顺便说一句,我正在使用 java 驱动程序和 spring-data mongodb。
请分享你的想法。谢谢 !
我检查了一个与我的嵌入式分页情况相关的旧问题。尽管带有切片的嵌入式分页工作正常,但仍然缺少总页面解决方案,我想知道是否有可能在服务器端获得评论的总大小。
有没有办法查询或计算服务器上嵌入数组的大小,而不必将整个文档提取到我的应用程序并手动计算它?
我不介意为此进行 2 次查询,1 次用于分页评论,1 次用于获取评论总数。如果我可以在一个查询中做到这一点,那将是惊人的。
顺便说一句,我正在使用 java 驱动程序和 spring-data mongodb。
请分享你的想法。谢谢 !
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)