使用聚合查找数组中对象的索引

Irf*_*han 4 javascript mongoose mongodb node.js

有没有办法在聚合管道中获取索引,我有一个长聚合查询的结果

[
    {
        "_id": "59ed949227ec482044b2671e",
        "points": 300,
        "fan_detail": [
            {
                "_id": "59ed949227ec482044b2671e",
                "name": "mila   ",
                "email": "mila@gmail.com ",
                "password": "$2a$10$J0.KfwVnZkaimxj/BiqGW.D40qXhvrDA952VV8x.xdefjNADaxnSW",
                "username": "mila  0321",
                "updated_at": "2017-10-23T07:04:50.004Z",
                "created_at": "2017-10-23T07:04:50.004Z",
                "celebrity_request_status": 0,
                "push_notification": [],
                "fan_array": [],
                "fanLength": 0,
                "celeb_bio": null,
                "is_admin": 0,
                "is_blocked": 2,
                "notification_setting": [
                    1,
                    2,
                    3,
                    4,
                    5,
                    6,
                    7
                ],
                "total_stars": 0,
                "total_points": 134800,
                "user_type": 2,
                "poster_pic": null,
                "profile_pic": "1508742289662.jpg",
                "facebook_id": "alistnvU79vcc81PLW9o",
                "is_user_active": 1,
                "is_username_selected": "false",
                "__v": 0
            }
        ]
    }
],
Run Code Online (Sandbox Code Playgroud)

所以我想找到聚合查询中的索引_id,上面的数组可以包含 100 个对象。

Nei*_*unn 6

根据可用的 MongoDB 版本,您有不同的方法:

$indexOfArray- MongoDB 3.4

最好的操作员就是$indexOfArray您可以使用的操作员。这个名字确实说明了一切:

Model.aggregate([
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } },

  { "$addFields": { 
    "fanIndex": {
      "$indexOfArray": [
        "$fan_detail._id",
        mongoose.Types.ObjectId("59ed949227ec482044b2671e")
      ]
    }
  }}
])
Run Code Online (Sandbox Code Playgroud)

$unwindincludeArrayIndex- MongoDB 3.2

返回到发行版中的某个版本,您可以通过 的语法从数组中获取索引$unwind。但这确实需要您的$unwind数组:

Model.aggregate([
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } },
  { "$unwind": { "path": "$fan_detail", "includeArrayIndex": true } },
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } }
])
Run Code Online (Sandbox Code Playgroud)

mapReduce - 早期版本

MongoDB 3.2 的早期版本无法在聚合管道中返回数组索引。因此,如果您想要匹配的索引而不是所有数据,那么您可以使用mapReduce

Model.mapReduce({
  map: function() {
    emit(
      this._id,
      this['fan_detail']
        .map( f => f._id.valueOf() )
        .indexOf("59ed949227ec482044b2671e") 
    )
  },
  reduce: function() {},
  query: { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") }
})
Run Code Online (Sandbox Code Playgroud)

在所有情况下,我们本质上都是事先“查询”数组中“某处”元素是否存在。“indexOf”变体将返回-1没有找到其他内容的地方。

这里也$addFields只是举例。如果您真正的意图是不返回包含 100 个项目的数组,那么您可能正在使用$project或其他输出。