The $sort modifier orders the elements of an array during a $push operation.
To use the $sort modifier, it must appear with the $each modifier. You can pass an empty array [] to the $each modifier such that only the $sort modifier has an effect.
To sort array elements that are not documents, or if the array elements are documents, to sort by the whole documents, specify 1 for ascending or -1 for descending.
If the array elements are documents, to sort by a field in the documents, specify a sort document with the field and the direction, i.e. { field: 1 } or { field: -1 }. Do not reference the containing array field in the sort specification (e.g. { “arrayField.field”: 1 } is incorrect).
Behavior
Changed in version 2.6.
The $sort modifier can sort array elements that are not documents. In previous versions, the $sort modifier required the array elements be documents.
If the array elements are documents, the modifier can sort by either the whole document or by a specific field in the documents. In previous versions, the $sort modifier can only sort by a specific field in the documents.
Trying to use the $sort modifier without the $each modifier results in an error. The $sort no longer requires the $slice modifier. For a list of modifiers available for $push, see Modifiers.
Examples
Sort Array of Documents by a Field in the Documents
A collection students contains the following document:
The sort document refers directly to the field in the documents and does not reference the containing array field quizzes; i.e. { score: 1 } and not { “quizzes.score”: 1}
After the update, the array elements are in order of ascending score field.:
A collection students contains the following document:
1
{ "_id" : 3, "tests" : [ 89, 70, 100, 20 ] }
To update the tests field to sort its elements in descending order, specify the { $sort: -1 } and specify an empty array [] for the $each modifier, as in the following:
Pipeline 模式的核心思想是将一个任务处理分解为若干个处理阶段(Stage),其中每个处理阶段的输出作为下一个处理阶段的输入,并且各个处理阶段都有相应的工作者线程去执行相应的计算。因此,处理一批任务时,各个任务的各个处理阶段是并行(Parallel)的。通过并行计算,Pipeline 模式使应用程序能够充分利用多核 CPU 资源,提高其计算效率。
Master-Slave 模式是一个基于分而治之(Divide and conquer)思想的设计模式。其核心思想是将一个任务(原始任务)分解为若干个语义等同(Semantically-identical)的子任务,并由专门的工作者线程来并行执行这些子任务。原始任务的处理结果是通过整合各个子任务的处理结果而形成的。而这些与分而治之相关的处理细节对于原始任务的提交方来说又是不可见的,因此,Master-Slave 模式既提高计算效率,又实现了信息隐藏。
如果并发任务的执行涉及某个非线程安全对象,而我们又希望因此而引入锁,那么我们可以考虑使用 Serial Thread Confinement 模式。
Serial Thread Confinement 模式的核心思想是通过将多个并发的任务存入队列实现任务的串行化,并为这些串行化的任务创建唯一的一个工作者线程进行处理。因此,这个唯一的工作者线程所访问的非线程安全对象由于只有一个线程访问它,对其的访问自然无需加锁,从而避免了锁的开销及由锁可能引发的问题。
当然,如果我们对并发任务访问的非线程安全对象进行加锁,也能实现任务的串行化从而实现线程安全,另外 Serial Thread Confinement 模式串行化并发任务所使用的队列本身也会涉及锁。因此,Serial Thread Confinement 模式的本质是使用一个开销更小的锁(串行化并发任务时所用队列涉及的锁)去替代另一个可能的开销更大的锁(为保障并发任务所访问的非线程安全对象可能引入的锁)。