我有一个简单的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},
])
答案 0 :(得分:0)
在聚合管道中,除了在组状态中使用的累加器之外的所有表达式都不维护状态,即它们不能引用先前文档中的字段。因此,仅使用Mongo查询不可能满足此要求。最好在应用程序代码中实现此逻辑。