In addition to the basic query capabilities, MONGODB provides powerful aggregation capabilities. This is mainly about count, distinct, and group.
1. Count:
--In an empty collection, Count returns a number of 0.
> Db.test.count ()
0
--Test the return value of count after inserting a document.
> Db.test.insert ({"Test": 1})
> Db.test.count ()
1
> Db.test.insert ({"Test": 2})
> Db.test.count ()
2
--count, like find, also accepts conditions. As you can see from the results, only eligible documents are involved in the calculation.
> Db.test.count ({"Test": 1})
1
2. Distinct:
Distinct is used to find all the different values for a given key. You must also specify collections and keys when you use them.
--to facilitate subsequent testing, empty the test collection.
> Db.test.remove ()
> Db.test.count ()
0
--Insert 4 test data. Please note the age field.
> Db.test.insert ({"Name": "Ada", "Age": 20})
> Db.test.insert ({"Name": "Fred", "Age": 35})
> Db.test.insert ({"Name": "Andy", "Age": 35})
> Db.test.insert ({"Name": "Susan", "Age": 60})
The--distinct command must specify the collection name, such as test, and the fields you want to differentiate, such as age.
-The following command executes the distinct command based on the age field in the Test collection.
> Db.runcommand ({"distinct": "Test", "Key": "Age"})
{
"Values": [
20,
35,
60
],
"Stats": {
"N": 4,
"Nscanned": 4,
"Nscannedobjects": 4,
"Timems": 0,
"Cursor": "Basiccursor"
},
"OK": 1
}
3. Group:
The aggregation made by group is somewhat complex. Select the key on which the group is based, and then mongodb the collection according to the selected key values to several groups. You can then produce a result document by aggregating the documents within each group.
--Here is the test data that is prepared
> Db.test.remove ()
> Db.test.insert ({"Day": "2012-08-20", "Time": "2012-08-20 03:20:40", "Price": 4.23})
> Db.test.insert ({"Day": "2012-08-21", "Time": "2012-08-21 11:28:00", "Price": 4.27})
> Db.test.insert ({"Day": "2012-08-20", "Time": "2012-08-20 05:00:00", "Price": 4.10})
> Db.test.insert ({"Day": "2012-08-22", "Time": "2012-08-22 05:26:00", "Price": 4.30})
> Db.test.insert ({"Day": "2012-08-21", "Time": "2012-08-21 08:34:00", "Price": 4.01})