在猫鼬中按日期分组

Nou*_*our 2 mongoose mongodb node.js

这是我的预约系列

{ _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" }
Run Code Online (Sandbox Code Playgroud)

我怎么能得到这样的resualt

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

我试试这个

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

请帮忙

Joh*_*yHK 6

使用$push聚合运算符在以下位置组装patients数组$group:

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

要在您的后续问题中包括患者ID:

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