【问题标题】:Social network query with MongoDB使用 MongoDB 进行社交网络查询
【发布时间】: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


【解决方案1】:

在聚合管道中,除了在组状态中使用的累加器之外的所有表达式都不维护状态,即它们不能引用以前文档中的字段。因此,仅使用 Mongo 查询是不可能满足这一要求的。最好在您的应用程序代码中实现此逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2015-01-30
    • 2013-08-22
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2011-05-15
    相关资源
    最近更新 更多