查找所有文档,但如果某些文档具有相同的值,则获取最新的文档

时间:2017-02-23 04:28:23

标签: javascript node.js mongodb mongoose

我会尝试用样本数据来解释。用户可以进行任何数量的评论,但我只想让评论者返回最新评论。

{   
    id : 1
    name : "John",
    review : "only one review"
    dateCreated : 2017-02-23 02:35:11.420Z
}
{   
    id : 3
    name : "Sam"
    review : "second entered"
    dateCreated : 2017-02-23 02:41:42.300Z
}
{   
    id : 2
    name : "Sam",
    review : "fist enterd"
    dateCreated : 2017-02-23 02:36:32.150Z
}

.find()应该返回id为1且id为3的文档。因为只有一个由John创建,而id为3的是由Sam创建的最后一个。

对此有疑问吗?

我的实际项目比较困难,因为name代替userIdanonId。这些字段的值为对象ID。而最复杂的部分是doc不包含两者。它包含userIdanonId

所以我想我可能需要一个或一个条件。 anonId或userId

也许你也可以给我这个想法。

编辑:

我的实际数据看起来更像是这样。它更复杂。

{
    anonId : ObjectId("58ae4f934a7d2b2490e8f99c")
    review : review made by an anoymous user
    dateCreated : 2017-02-23 02:35:11.420Z
}
{
    anonId : ObjectId("58ae4f934a7d2b2490e8f99c")
    review : second review made by anonymous user
    dateCreated : 2017-02-23 05:35:11.420Z
}
{
    userId : ObjectId("58ae4a5f4a7d2b2490e8f996")
    review : first review made by authenticated user
    dateCreated : 2017-02-22 05:35:11.420Z
}
{
    userId : ObjectId("58ae4a5f4a7d2b2490e8f996")
    review : second review made by authenticated user
    dateCreated : 2017-02-25 05:35:11.420Z
}

{
    userId : ObjectId("58ae5fc7a467cf23947833c8")
    review : This will be returened because no other review has this userID
    dateCreated : 2017-02-25 05:35:11.420Z
}

1 个答案:

答案 0 :(得分:1)

您可以$sortdateCreated$groupuserIdanonId上执行降序db.test.aggregate([{ $sort: { "dateCreated": -1 } }, { $project: { ref: { $cond: { if: { $gt: ["$userId", null] }, then: "$userId", else: "$anonId" } }, document: "$$ROOT" } }, { $group: { _id: "$ref", document: { "$first": "$document" } } }])

$project

请注意,userId阶段中使用的条件是检查ref是否存在其他设置anonId» Request.where("name_id = ? OR customer_id =? OR (name_id IN (?) && customer_id IN (?))", user, user, [ids], [ids])

Here是一个要点