0

Query: select count(distinct finish_date), sum(study_num) from table where student_id=1234

Documents:

{
    "_id" : ObjectId("602252684a43d5b364f3e6ca"),
    "student_id" : 1234,
    "study_num" : 8,
    "finish_date" : "20210209",
},
{
    "_id" : ObjectId("602257594a43d5b364f4cc6a"),
    "student_id" : 1234,
    "study_num" : 7,
    "finish_date" : "20210207",
},
{
    "_id" : ObjectId("5fbb65580d685b17fa56e18f"),
    "student_id" : 2247,
    "study_num" : 6,
    "finish_date" : "20210209",
}
1

2 Answers 2

0

You can use $match and $group

db.collection.aggregate([
  {
    "$match": {"student_id": 1234}
  },
  {
    "$group": {
      "_id": "$finish_date",
      "study_sum": { $sum: "$study_num" }
    }
  },
  {
    "$group": {
      "_id": null,
      "study_sum": { $sum: "$study_sum" },
      count: { $sum: 1 }
    }
  }
])

Working Mongo playground

Sign up to request clarification or add additional context in comments.

4 Comments

Your answer's result is not i want. Your result:[{"study_sum":8,"count":1},{"study_sum":7,"count":1}]. I want:[{"study_sum":15,"count":2}]
@Grug what is your expected result
your updated answer's "study_sum" is right, but "count" is not distinct. if i modify "20210207" to "20210209", your answer's "count" is 2, but the expected is 1
@Grug I have updated my answer, let me know if you need help
0

Query: select count(distinct finish_date), sum(study_num) from table where student_id=1234

How to write the query? Write using an aggregation:

db.collection.aggregate([
  { 
    $match: { student_id: 1234 } 
  },
  { 
    $group: {
         _id: "", 
         distinct_dates: { $addToSet: "$finish_date"  }, 
         study_sum: { $sum: "$study_num" } 
    } 
  },
  { 
    $project: { 
        count: { $size: "$distinct_dates" }, 
        study_sum: 1, _id: 0 
    } 
  }
])

The output: { "study_sum" : 15, "count" : 2 }

Reference: SQL to Aggregation Mapping Chart

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.