Group It takes about a few parameters.
- Key: The field used to group the document. And Keyf both must have a
- KEYF: You can accept a JavaScript function. The field used to dynamically determine the grouped document. And key both must have a
- Initialization of variables used in Initial:reduce
- Reduce: The reduce function that is executed. The function needs to return a value.
- Cond: The condition to perform the filtering.
- Finallize: At reduce execution completion, the result set returns the function that was eventually executed against the result set. An optional
Test data
Test Data Db.stocks.insert ({"Day": "2010/10/03", "Time": "2010/10/03 03:47:01 GMT-400", "Price": 4.23}); Db.stocks.insert ({"Day": "2010/10/04", "Time": "2010/10/04 11:28:39 GMT-400", "Price": 4.27}); Db.stocks.insert ({"Day": "2010/10/03", "Time": "2010/10/03 05:00:23 GMT-400", "Price": 4.10}); Db.stocks.insert ({"Day": "2010/10/06", "Time": "2010/10/06 05:27:58 GMT-400", "Price": 4.30}); Db.stocks.insert ({"Day": "2010/10/04", "Time": "2010/10/04 08:34:50 GMT-400", "Price": 4.01});
Test the Group program code to be executed
Db.runcommand ({"group": { "ns": "Stocks", " Key": "Day", "initial": {"Time": 0}, "$reduce": function ( Doc, prev) { if (Doc.time > Prev.time) { prev.price = Doc.price; Prev.time = Doc.time; } }
Results after the execution
{" retval": [ { "time": 0 } ], "Count": 5, "keys": 1, "OK": 1 }
MongoDB Learning-Advanced query [aggregation Group]