在数组聚合中设置索引范围 MongoDB

Set range of indexes in array aggregation MongoDB

我的数据库看起来像:

{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'}}])

感谢您的帮助

$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/