MongoDB $ slice (built-in swap array)

I have this circuit:

article: { subject, comments: [] } 

if I have 8 comments and request

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

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

now I need to pass another parameter "lastId" to compare each comment and remove the "_id" <"lastId", but I think it is a bit hacked.

Who has a good solution for this?

+6
source share
1 answer

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

When you add embedded documents to an array that is not a fixed size, mongoDB can potentially move the document as it grows by changing the fill factor and causing fragmentation (fill factor is an assumption from the mongodb side on how big your document will grow, it allocates more space for this occasion).

You are also limited to the 16MB pr document, so imagine if you get a crazy popular stream, or you decide to extend comments with other metadata as much as possible that you break this barrier. Getting a large document is also expensive and time consuming.

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

There is a good presentation under

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

I think that in the near future there will be more work on the design of the circuit, which will be more useful in the long term. I think that would be very difficult, to be honest. I know it took me a while to wrap my head around the differences from relational models.

+13
source

Source: https://habr.com/ru/post/914769/


All Articles