获取数组中元素的索引

时间:2016-05-03 13:27:14

标签: node.js mongodb mongoose

请注意以下架构:

Client {
 name: String
}

Votes {
 start: Date,
 end: Date,
 clients: [
  client: Client,
  votes: Number
 ]
}

是否可以在'votes.clients'中获取某个'Client'的索引而不返回整个数组?

我的用例如下。 'clients'数组按投票数排序。阵列中可能有数十万个元素。我需要在一段时间内快速获得某些客户的投票数量。例如:'昨天,客户John按投票数排名第205位。

1 个答案:

答案 0 :(得分:0)

当您在某个时刻订购客户端数组时,您可以将索引值保留在子文档中。

 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]}
                }
            }
        }
    }
])
相关问题