0

我的conversations收藏中有一些如下形式的文档,可以在多人之间进行聊天。threadId 保存 2 之间对话中的用户之一的 id。

51c0c35b7daabc3410000001和之间的对话51c0c35b7daabc3410000002

{
    "from" : ObjectId("51c0c35b7daabc3410000001"), 
    "to" : ObjectId("51c0c35b7daabc3410000002"),
    "threadId" : ObjectId("51c0c35b7daabc3410000002"),
    "message" : "Hi there!"
}

{
    "from" : ObjectId("51c0c35b7daabc3410000002"),
    "to" : ObjectId("51c0c35b7daabc3410000001"),
    "threadId" : ObjectId("51c0c35b7daabc3410000002"),
    "message" : "How are you?"
}

{
    "from" : ObjectId("51c0c35b7daabc3410000001"), 
    "to" : ObjectId("51c0c35b7daabc3410000002"),
    "threadId" : ObjectId("51c0c35b7daabc3410000002"),
    "message" : "I am good. How are you?"
}

51c0c35b7daabc3410000001和之间的对话51c0c69989a44a6812000003

{
    "from" : ObjectId("51c0c35b7daabc3410000001"), 
    "to" : ObjectId("51c0c69989a44a6812000003"),
    "threadId" : ObjectId("51c0c69989a44a6812000003"),
    "message" : "Hello!"
}

{
    "from" : ObjectId("51c0c69989a44a6812000003"), 
    "to" : ObjectId("51c0c35b7daabc3410000001"),
    "threadId" : ObjectId("51c0c69989a44a6812000003"),
    "message" : "Hey.."
}

我想根据 threadId 进行分组,输出的形式应该是

{
    "from" : ObjectId("51c0c35b7daabc3410000001"), 
    "to" : ObjectId("51c0c35b7daabc3410000002"),
    "threadId" : ObjectId("51c0c35b7daabc3410000002"),
    "message" : "I am good. How are you?"
}

{
    "from" : ObjectId("51c0c69989a44a6812000003"), 
    "to" : ObjectId("51c0c35b7daabc3410000001"),
    "threadId" : ObjectId("51c0c69989a44a6812000003"),
    "message" : "Hey.."
}

所以我想找到所有具有不同 threadId 的文档(或仅基于 threadId 的组)。输出还应包括文档中的所有其他字段。

mapReduce,聚合/组,不同的或这些的组合?我该怎么做?

编辑

把它放在 SQL 语句中,我想要一些简单的东西

SELECT * FROM conversations GROUP BY threadId;

4

1 回答 1

0

我最终这样做了

// Aggregate pipeline
Conversation.aggregate(
    { $match: {
        listing: new ObjectId(listingId)
      }
    },
    { $group: {
        _id: '$threadId', 
        message: { $last: "$message" },
        to: { $last: "$to" },
        from: { $last: "$from" }
      }
    },
    { $project : {
        _id : 0,
        threadId : "$_id",
        message: "$message",
        to: "$to",
        from: "$from"
      }
    },
    function(err, threads) {
        console.log(err);
        console.log(threads);
    }
);

它似乎工作正常。让我知道是否有任何更简单的方法或者是否可以优化此代码段。希望这可以帮助某人。

于 2013-06-21T06:02:50.360 回答