0

I have an object structure as shown below

{
    "_id" : ObjectId("55d164f1c8f2c53a82535b9a"),
    "plant_name" : "TOTAL",
    "installed_capacity" : 3473,
    "wind_data" : [ 
        {
            "date" : "16-08-15",
            "timestamp" : " 16:27:15",
            "generated_capacity" : 617.24,
            "frequency" : 50.01
        }, 
        {
            "date" : "16-08-15",
            "timestamp" : " 21:21:15",
            "generated_capacity" : 670.25,
            "frequency" : 49.94
        }, ....]
}

I need to sum up (at least retrieve) "generated_capacity" of all the objects under "wind_data" having "date" equal to "16-08-15" of "TOTAL" object. I have tried this query

   db.collectionName.aggregate(
      {"$unwind":"$wind_data"},
      {"$match":{"plant_name":"TOTAL","wind_data.date":"16-08-15"}}
      )

But, this query is not working. Please suggest some way to figure this out.

10
  • You are missing a closing quote, and you really should also $match first as well, but otherwise this should be working up to this point. What is wrong? Commented Aug 17, 2015 at 6:51
  • It returns all the fields of the object. How to find the sum of particular field inside the array. Like "generated_capacity" inside the array. Commented Aug 17, 2015 at 6:56
  • add this after match {"$group":{"_id":"$wind_data.date","generated_capacity_sum":{"$sum":"$generated_capacity}}} Commented Aug 17, 2015 at 6:58
  • This is a very basic operation. You should spend some time reading SQL to Aggregation Mapping Chart which includes things like this as common examples. Commented Aug 17, 2015 at 7:01
  • Thanks @BlakesSeven . i am two days old to this querying in mongodb. Couldnt find any useful material. Anyway thanks for sharing. Will build upon this Commented Aug 17, 2015 at 7:06

1 Answer 1

0

The following query would do the job

    db.collectionName.aggregate([      
      {"$unwind":"$wind_data"},       
      {"$match":{"plant_name":"TOTAL","wind_data.date":"16-08-15"}},
      {"$group":{"_id":"$wind_data.date","generated_capacity_sum":{"$sum":"$wind_data.generated_capacity"}}}
    ])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.