Nour Sammour
Nour Sammour

Reputation: 2852

Group by date in mongoose

this is my appointment collection

{ _id: ObjectId("518ee0bc9be1909012000002"), date: ISODate("2013-05-13T22:00:00Z"), patient:"John" }

{ _id: ObjectId("518ee0bc9be1909012000002"), date: ISODate("2013-05-13T22:00:00Z"), patient:"alex" }

{ _id: ObjectId("518ee0bc9be1909012000002"), date: ISODate("2013-05-13T22:00:00Z"), patient:"sara" }

how can i get my resualt like this

{date: ISODate("2013-05-13T22:00:00Z"),
patients:["John","alex","sara"] }

i try this

Appointments.aggregate([
{
$group: {
_id: '$date'
}
}
], function(err, doc) {
return console.log(JSON.stringify(doc));
});

any help please

Upvotes: 3

Views: 7674

Answers (2)

ahmed ali
ahmed ali

Reputation: 11

exports.getAllBokFilterByDate = async (req, res) => {
  try {
    const data = await Book.aggregate([
      {
        $group: {
          _id: {$dateToString:{format:"%Y-%m-%d",date:"$date"}},
          count: { $sum: 1 } 
        }
      }
    ]);

    res.status(200).json({
      data
    });
  } catch (error) {
    res.status(400).json({
      status: 'failed',
      error
    });
  }
};

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311865

Use the $push aggregation operator to assemble the patients array in the $group:

Appointments.aggregate([
    {$group: {_id: '$date', patients: {$push: '$patient'}}},
    {$project: {date: '$_id', patients: 1, _id: 0}}
], ...)

To include the patient ids as in your follow-up question:

Appointments.aggregate([
    {$group: {_id: '$date', patients: {$push: {
        patient: '$patient'
        _id: '$_id'
    }}}},
    {$project: {date: '$_id', patients: 1, _id: 0}}
], ...)

Upvotes: 10

Related Questions