Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

For example, I have the following document in MongoDB:

{ "_id" : ObjectId("524091f99c49c4c3f66b0e46"), "hour" : 10, "incoming", 100}

{ "_id" : ObjectId("5240a045dbeff33c7333aa51"), "hour" : 11, "incoming", 200}

{ "_id" : ObjectId("5240a2ecda0d37f35c618aca"), "hour" : 12, "incoming", 300}

From the above document database, I want to query "SUM the number of incoming between 11 - 12" 

the output should be 500, how can I perform that using Mongo Shell?

1 Answer

0 votes
by (107k points)
edited by

 The solution to your problem is the aggregation framework that mongodb provides. Here's what your query would look like:

db.CollectionNameGoesHere.aggregate({ $match: {

    $and: [

        { hour: { $gte: 11 } },

        { hour: { $lte: 12 } }

    ]

} },

{ $group: { _id : null, sum : { $sum: "$incoming" } } });

You can also shape the resulting document to only contain the sum by adding a $project operator at the end of the pipeline, like so:

{ $project: { _id: 0, sum: 1 } }

If you want more information regarding the same kindly refer to the following mongodb tutorial 

Want to learn MongoDB from the experts, Check out this MongoDB Course in Sydney to enhance your Knowledge!

Related questions

0 votes
1 answer
asked Mar 15, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Mar 14, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Feb 2, 2020 in Web Technology by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...