【问题标题】:Group by date in mongoose在猫鼬中按日期分组
【发布时间】:2013-05-19 23:06:26
【问题描述】:

这是我的约会收藏

{ _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" }

我怎样才能得到这样的结果

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

我试试这个

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

请帮忙

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    使用$push聚合运算符将patients数组组装到$group中:

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

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

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

    【讨论】:

    • 谢谢.... 怎么能用病人推 _id ??? {日期:ISODate("2013-05-13T22:00:00Z"),患者:[{_id :518ee0bc9be1909012000002,患者:“约翰”},{_id :518ee0bc9be1909012000002,患者:“alex”},{_id :518ee0009be19090120,病人:“萨拉”}] }
    • 这是在架构中完成还是在我们使用 .find() 的路由中完成
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 2012-02-17
    • 2020-07-10
    相关资源
    最近更新 更多