-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
last.txt
82 lines (59 loc) · 2.54 KB
/
last.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
===================
$last (aggregation)
===================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. group:: $last
Returns the value that results from applying an expression to the
last document in a group of documents that share the same group by
a field. Only meaningful when documents are in a defined order.
.. include:: /includes/extracts/fact-aggregation-accumulator-last.rst
:expression:`$last` has the following syntax:
.. code-block:: javascript
{ $last: <expression> }
For more information on expressions, see :ref:`aggregation-expressions`.
Behavior
--------
When using :group:`$last` in a :pipeline:`$group` stage, the
:pipeline:`$group` stage should follow a :pipeline:`$sort` stage to
have the input documents in a defined order.
.. include:: /includes/note-group-pipeline-sort-order.rst
Example
-------
Consider a ``sales`` collection with the following documents:
.. code-block:: javascript
{ "_id" : 1, "item" : "abc", "date" : ISODate("2014-01-01T08:00:00Z"), "price" : 10, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "date" : ISODate("2014-02-03T09:00:00Z"), "price" : 20, "quantity" : 1 }
{ "_id" : 3, "item" : "xyz", "date" : ISODate("2014-02-03T09:05:00Z"), "price" : 5, "quantity" : 5 }
{ "_id" : 4, "item" : "abc", "date" : ISODate("2014-02-15T08:00:00Z"), "price" : 10, "quantity" : 10 }
{ "_id" : 5, "item" : "xyz", "date" : ISODate("2014-02-15T09:05:00Z"), "price" : 5, "quantity" : 10 }
{ "_id" : 6, "item" : "xyz", "date" : ISODate("2014-02-15T12:05:10Z"), "price" : 5, "quantity" : 5 }
{ "_id" : 7, "item" : "xyz", "date" : ISODate("2014-02-15T14:12:12Z"), "price" : 5, "quantity" : 10 }
The following operation first sorts the documents by ``item`` and
``date``, and then in the following :pipeline:`$group` stage, groups
the now sorted documents by the ``item`` field and uses the
:group:`$last` accumulator to compute the last sales date for each item:
.. code-block:: javascript
db.sales.aggregate(
[
{ $sort: { item: 1, date: 1 } },
{
$group:
{
_id: "$item",
lastSalesDate: { $last: "$date" }
}
}
]
)
The operation returns the following results:
.. code-block:: javascript
{ "_id" : "xyz", "lastSalesDate" : ISODate("2014-02-15T14:12:12Z") }
{ "_id" : "jkl", "lastSalesDate" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : "abc", "lastSalesDate" : ISODate("2014-02-15T08:00:00Z") }