paulkon
paulkon

Reputation: 1855

What is the difference between $push/$sort and .sort() at query time?

So, for retrieval purposes, what is the difference between the two? I think the $push/$sort feature is new to in 2.4 yet I still don't understand how this would be any different than using .sort() on the sub-document array while querying for the parent. Is using $push/$sort a better approach? Does it save the use of an index on the subdoc array?

Upvotes: 1

Views: 348

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

2.4 introduced a feature that allows you to keep only "last/best/top/first" N elements of an array when you $push new values to it during an update. The way you do it is by specifying the field and direction to use for $sort and $slice to tell it how many to keep.

When you query and use sort() that applies to the documents that are being returned, not to elements of arrays inside of such documents.

See more description of the capped array feature here.

Upvotes: 2

Related Questions