【问题标题】:find all the documents that is the latest by a field and distinct by another field in mongodb collection在 mongodb 集合中按一个字段查找最新且由另一个字段不同的所有文档
【发布时间】:2015-10-16 21:21:18
【问题描述】:

我想将整个文档提取到组中。

例如,我有一个名为“sub_comment”的集合。

每个“sub_comment”都有一个对“comment”之一的引用作为“commentId”。

sub_comment = new Schema({  // as per mongoose schema
   updatedAt : Date,
   text : String,
   by : String,
   info : String,
   commentId : { type : ObjectId, ref : 'commment' }
})

现在我想提取按每条评论分组的所有最新的子集(完整文档)(通过“updatedAt”)。

我目前正在这样做:

mongoose.model('sub_comment').aggregate([
            { $sort: { commentId : 1, updatedAt: -1 } },
            { $group: { _id: "$commentId", updatedAt: { $first: "$updatedAt" } } }
          ]

当然,这只会返回两个字段,即updatedAtcommentId

现在,如果我想要整个文档怎么办。我将不得不单独编写每个字段,我不想这样做。

首选的方法应该是什么?

编辑:简单查询

收藏=

[
{commentId : 1, updatedAt : ISO("2015-10-13T11:38:29.000Z"), xyz  : 'xyz1' },
{commentId : 2, updatedAt : ISO("2015-10-10T11:38:29.000Z"), xyz  : 'xyz2'  },
{commentId : 2, updatedAt : ISO("2015-10-14T11:38:29.000Z"), xyz  : 'xyz3'  },
{commentId : 1, updatedAt : ISO("2015-10-11T11:38:29.000Z"), xyz  : 'xyz4'  }
]

我想要输出:

[
{commentId : 1, updatedAt : ISO("2015-10-13T11:38:29.000Z"), 'xyz' : 'xyz1' },
{commentId : 2, updatedAt : ISO("2015-10-14T11:38:29.000Z"), 'xyz' : 'xyz3'  }
]

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您可以在聚合中使用$$ROOT 系统变量来引用管道中该阶段的完整顶级文档:

    mongoose.model('sub_comment').aggregate([
            { $sort: { commentId : 1, updatedAt: -1 } },
            { $group: { _id: "$commentId", doc: { $first: "$$ROOT" } } }
          ]
    

    【讨论】:

    • MongoError: 异常:FieldPath 字段名称可能不以'$'开头
    • $$ROOT 是在 MongoDB 2.6 中添加的,因此请确保您的服务器是该版本或更高版本。
    • ok 我的是 2.4.5,但是在迁移 mongo 之后,你确定,我不会得到这种错误:[MongoError: exception: group aggregate field 'doc' must be defined as an对象内的表达式] ????
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多