[英]How to get the index of an array element in older versions on Mongodb?
[英]Get index of element in array
请注意以下架构:
Client {
name: String
}
Votes {
start: Date,
end: Date,
clients: [
client: Client,
votes: Number
]
}
是否有可能在'votes.clients'中获取某个'Client'的索引而不返回整个数组?
我的用例如下。 'clients'数组按投票数排序。 阵列中可能有数十万个元素。 我需要在一段时间内快速获得某些客户的投票数量。 例如:'昨天,客户John按投票数排名第205位。
当您在某个时刻订购clients数组时,可以将索引值保留在子文档中。
clients: [
{
client: {type: mongoose.Schema.Types.ObjectId, ref: 'Client'},
votes: {type: Number},
index: {type: Number}
}
]
在聚合框架中使用$ filter将仅返回与筛选条件匹配的子文档,并且它们将包含索引。
Vote.aggregate( [{ $match: {end: "2016-10-14T19:39:52.476Z"}},
{
$project: {
clients: {
$filter: {
input: '$clients',
as: 'client',
cond: {$gt: ['$$client.votes', 50]}
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.