【问题标题】:Get index of element in array获取数组中元素的索引
【发布时间】:2016-10-15 04:20:12
【问题描述】:

遵守以下模式:

Client {
 name: String
}

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

是否可以在不返回整个数组的情况下获取“votes.clients”中某个“客户端”的索引?

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    当您在某个时候对客户端数组进行排序时,您可以将索引值保留在子文档中。

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

    【讨论】:

      猜你喜欢
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多