Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $sum:1 mean in Mongo

Tags:

mongodb

I have a collection foo:

{ "_id" : ObjectId("5837199bcabfd020514c0bae"), "x" : 1 }
{ "_id" : ObjectId("583719a1cabfd020514c0baf"), "x" : 3 }
{ "_id" : ObjectId("583719a6cabfd020514c0bb0") }

I use this query:

db.foo.aggregate({$group:{_id:1, avg:{$avg:"$x"}, sum:{$sum:1}}})

Then I get a result:

{ "_id" : 1, "avg" : 2, "sum" : 3 }

What does {$sum:1} mean in this query?

like image 996
Alex Belke Avatar asked Nov 24 '16 17:11

Alex Belke


People also ask

What does sum 1 do in MongoDB?

1 Answer. In MongoDB, the $sum will add up the value of the expression for every row and in your case, you are having 3 rows so it will be 1+1+1 =3.

What is sum in MongoDB?

Definition. $sum. Changed in version 5.0. Calculates and returns the collective sum of numeric values. $sum ignores non-numeric values.

How does MongoDB calculate sum of salary?

$sum operator returns the sum of all numeric values of documents in the collection in MongoDB. Above will create collection (or table) (if collection already exists it will insert documents in it). Step 2.1 - We will group employee by firstName and find sum of salary of each group.

What is $$ now in MongoDB?

$$NOW is an aggregation variable, which means that it can by used only within aggregation pipeline. Due to the documentation, save() method is deprecated. use insertOne() instead. To insert current date you need to provide date value on the client side.


2 Answers

From the official docs:

When used in the $group stage, $sum has the following syntax and returns the collective sum of all the numeric values that result from applying a specified expression to each document in a group of documents that share the same group by key:

{ $sum: < expression > }

Since in your example the expression is 1, it will aggregate a value of one for each document in the group, thus yielding the total number of documents per group.

like image 169
jnovo Avatar answered Oct 02 '22 01:10

jnovo


Basically it will add up the value of expression for each row. In this case since the number of rows is 3 so it will be 1+1+1 =3 . For more details please check mongodb documentation https://docs.mongodb.com/v3.2/reference/operator/aggregation/sum/

For example if the query was:

db.foo.aggregate({$group:{_id:1, avg:{$avg:"$x"}, sum:{$sum:$x}}})

then the sum value would be 1+3=4

like image 30
Swetha Avatar answered Oct 01 '22 23:10

Swetha