【问题标题】:Set range of indexes in array aggregation MongoDB在数组聚合MongoDB中设置索引范围
【发布时间】:2018-12-15 02:25:32
【问题描述】:

我的数据库如下所示:

{email:"user", contacts: 
 [
  {emailContact:"test", firstName:"test", lastName:"test", messages:
   [
    {email:"user", content:"hi", date:"ISODate(...)"}
    {email:"test", content:"how are you?", date:"ISODate(...)"}
    {email:"user", content:"im fine", date:"ISODate(...)"}
   ]
  },
  {emailContact:test2, firstName:"test2", lastName:"test2", messages:
   [
    {email:"user", content:"hahaha", date:"ISODate(...)"}
    {email:"test2", content:"yea thats right", date:"ISODate(...)"}
    {email:"user", content:"xd", date:"ISODate(...)"}
   ]
  }
 ]
}

而且我必须获取特定索引的消息。 例如索引为 4,5,6 的消息。

我已经尝试了几个类似的:

db.contacts.aggregation([{$match:{email:"elo@elo.pl"}},{$unwind:'$contacts'},{$match:{'contacts.emailContact':'user@user.pl'}},{$unwind:'$contacts.messages'},{$project:{email:1,content:1,date:{$slice:['$contacts.messages',4,6]}}},{$replaceRoot:{newRoot:'$contacts.messages'}}])

感谢您的帮助

【问题讨论】:

    标签: arrays mongodb range aggregation


    【解决方案1】:

    $skip$limit 是你的朋友。

    假设您必须从 4 到 6 获取消息,您将 $skip 前三个文档和 $limit 您的结果以获取您想要的文档数量(在这种情况下也是三个,因为您想要 4、5、 6):

    db.contacts.aggregate([
      {$match: {email: 'user'}},
      {$unwind: '$contacts'},
      {$match: {'contacts.emailContact': 'test'}},
      {$unwind: '$contacts.messages'},
      {$sort: {'contacts.messages.date': -1}},
      {$skip: 3},
      {$limit: 3},
      {$replaceRoot: {newRoot: '$contacts.messages'}}
    ])
    

    无论如何,我建议您查看有关聚合的文档,它写得很好并且充满了示例:https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多