【发布时间】:2016-10-12 13:51:21
【问题描述】:
我有一个简单的 MongoDB 社交网络实现。我的架构如下所示:
User
_id
name
Friend
_id
user
friend
Post
_id
user
timestamp
text
我正在尝试使用aggregate 方法来获取我所有朋友的最新帖子列表,但我想将来自同一用户的连续帖子组合在一起。所以假设我有 3 个朋友,他们有以下帖子:
{"user": "user1", timestamp: 1476200010, text: "hello1"}
{"user": "user2", timestamp: 1476200009, text: "hello2"}
{"user": "user2", timestamp: 1476200008, text: "hello3"}
{"user": "user3", timestamp: 1476200007, text: "hello4"}
{"user": "user2", timestamp: 1476200006, text: "hello5"}
{"user": "user2", timestamp: 1476200005, text: "hello6"}
{"user": "user1", timestamp: 1476200004, text: "hello7"}
{"user": "user1", timestamp: 1476200003, text: "hello8"}
因此,我希望收到以下信息:
{"user": "user1", timestamp: 1476200010, text: "hello1"}
{"user": "user2", timestamp: 1476200009, text: "hello2"}
{"user": "user3", timestamp: 1476200007, text: "hello4"}
{"user": "user2", timestamp: 1476200006, text: "hello5"}
{"user": "user1", timestamp: 1476200004, text: "hello7"}
我的查询有点卡住了,感谢任何帮助:
db.Post.aggregate([
{$sort: {timestamp: -1}},
{$lookup: {from: 'Friend', localField: '_id', foreignField: 'friend', as: 'friend'}},
{$match: {'friend.user': current_user}},
???
{$limit: 100},
])
【问题讨论】:
-
关于这个问题,
aggregate不支持涉及相邻文档的操作,所以我认为您需要在应用程序代码中进行连续的后期修剪。
标签: node.js mongodb mongodb-query aggregation-framework