Mongoose返回10结果按日期排序的每个用户ID中的ID数组
假设我们有一个用户 id 数组:
"ids": [
"623d71c628820d09797be558",
"62419d6477775214de099838",
"62419d7877775214de099845",
"62419d8877775214de09984c"
]
我们想要返回每个 id 的前 10 个文档(按日期排序)。我知道我们可以这样做:
const docs = await Model.find({ id: { $in: ids } })
.sort("date")
.limit(10);
它返回按日期排序的 10 个文档,但不是针对每个用户,我如何为数组中的每个文档返回 10 个文档?
** 编辑 **
这是来自 balance
集合的示例文档:
{
"_id": "624a19a0b1cf7d69a5193737",
"user": {
"name": "john",
"id": "623d71c628820d09797be558"
},
"description": "chips",
"amount": 2,
"type": "expense",
"date": "2022-04-03T22:03:12.774Z",
"__v": 0
}
和“用户”文档:
{
"_id": "623d71c628820d09797be558",
"name": "john",
"__v": 0
}
lets say we have an array of user ids :
"ids": [
"623d71c628820d09797be558",
"62419d6477775214de099838",
"62419d7877775214de099845",
"62419d8877775214de09984c"
]
and we want to return the first 10 documents of every id sorted by date. I know we can do :
const docs = await Model.find({ id: { $in: ids } })
.sort("date")
.limit(10);
which returns 10 documents sorted by date,but not for every user,how could i return 10 for every one in array ?
** EDIT **
Here's an example document from the balance
collection:
{
"_id": "624a19a0b1cf7d69a5193737",
"user": {
"name": "john",
"id": "623d71c628820d09797be558"
},
"description": "chips",
"amount": 2,
"type": "expense",
"date": "2022-04-03T22:03:12.774Z",
"__v": 0
}
and a "user" document :
{
"_id": "623d71c628820d09797be558",
"name": "john",
"__v": 0
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您可以使用聚合管道进行的一种方法。
尝试一下 mongoplayground.net.net 。
Here's one way you could do it using an aggregation pipeline.
Try it on mongoplayground.net.