簡體   English   中英

獲取數組中元素的索引

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM