1

My MongoDB document looks like below:

{
    "_id" : ObjectId("5fb1828a6dbd2e5c533e2378"),
    "email" : "[email protected]",
    "fname" : "JOSE",
    "appt" : [ 
        {
            "date" : "12/04/2020",
            "time" : "0900",
        },
        {
            "date" : "12/05/2020",
            "time" : "1000",
        },
    ]
}

Both appt.date and appt.time are String!

I need to filter the records that contain array value appt.date: "12/04/2020". Then find all distinct appt.time values for given date along with its count.

I tried to use the pipeline aggregation but just cannot get it to work. How can I solve this in MongoDB 2.6.11?

0

1 Answer 1

1

You can try,

  • $match appt.date condition to filter main document
  • $unwind deconstruct appt array
  • $match appt.date condition again to filter sub document
  • $group by null and make time unique using $addToSet array
  • $addFields to get count of total time
db.collection.aggregate([
  { $match: { "appt.date": "12/04/2020" } },
  { $unwind: "$appt" },
  { $match: { "appt.date": "12/04/2020" } },
  {
    $group: {
      _id: null,
      time: { $addToSet: "$appt.time" }
    }
  },
  {
    $project: {
      _id: 0,
      time: 1,
      count: { $size: "$time" }
    }
  }
])

Playground

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.