MongoDB $ slice(嵌入式数组分页) [英] MongoDB $slice (embedded array paging)

查看:231
本文介绍了MongoDB $ slice(嵌入式数组分页)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个模式:

article: {
    subject,
    comments: []
}

如果我有8条评论,并进行查询

if I have 8 comments, and query

 article.find({}, {
     comments: {
         $slice: [ -10, 5 ]
     }
 });

然后我得到了从索引0到索引4的注释,
但我只希望由于分页而返回从索引0到索引2的注释.
(从索引3到索引7的页面1 $ slice [-5,5],从索引0到索引2的页面2 $ slice [-10,5]从索引0到索引2)

And I get comments from index 0 to index 4,
but I only want comments from index 0 to index 2 to be returned because of paging.
(page 1 $slice[ -5, 5 ] from index 3 to index 7, page 2 $slice[ -10, 5 ] from index 0 to index 2)

现在我必须传递另一个参数"lastId"来比较每个注释并删除该"_id"< "lastId",但我认为它有点hacky.

now I have to pass another parameter "lastId" to compare each comments and remove that "_id" < "lastId", but I think it is a little hacky.

有人对此有很好的解决方案吗?

Any one has a good solution for this?

推荐答案

所以我要说的是,您应该切换架构以将注释保留为单独的文档,因为这是一个未绑定的数组,它将使您的查询更高效.我会解释的.

So I'm going to say that you should switch your schema to leave comments as separate documents as this is an unbound array and it will make your queries more efficient. I'll explain it.

当您将嵌入式文档添加到非固定大小的数组中时,mongoDB可能会随着文档的增长而移动文档,从而更改填充因子并导致碎片化(填充因子是从mongodb的角度猜测的大小)您的文档将会增长,它将为这种情况预分配更多空间).

When you add embedded documents to an array that is not a fixed size mongoDB will potentially need to move the document around as it grows, changing the padding factor and causing fragmentation (the padding factor is a guess from mongodb's side off how big your document will grow, it preallocates more space for that case).

您也只能使用16MB的PR文档,因此,想象一下,如果您遇到了一个疯狂的流行线程,或者您决定使用其他元数据扩展注释,那么打破这一障碍是可行的.检索大文档也是昂贵且耗时的.

You are also limited to 16MB pr document so imagine if you get a crazy popular thread or you decide to extends comments with other metadata it's feasible that you'll break that barrier. Retrieving a big document is also expensive and time consuming.

通常,如果嵌入式文档不是未绑定的数组,则效果很好.因此,保留前10条评论的列表将非常有用,但保留1000条以上的评论是不好的.

In general embedded documents are great if they are not unbound arrays. So keeping a list of the top 10 comments will work great but keeping 1000+ comments is bad.

下面有一些不错的演示文稿

There are some good presentation under

http://www.10gen.com/演示文稿/mongodb-berlin/2012/10-key-performance-indicators http://www.10gen.com/presentations/mongosv-2011 /schema-design-by-example

我认为,架构设计方面不久将会有更多工作,从长远来看会有所帮助.我认为这是最困难的事情.我知道,我花了一些时间来思考与关系模型之间的差异.

I think there is more work coming soon on schema design that will more helpful in the long term. I think it's the hardest bit to be honest. I know, it took me awhile to wrap my head around the differences from relational models.

这篇关于MongoDB $ slice(嵌入式数组分页)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆