MongoDB:聚合元素值为'x'的对象数组中的索引值

MongoDB: Aggregate the index value in array of objects with element value of 'x'

我正在尝试从文档的这一部分开始工作:https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfArray/

我的用例几乎相同,除了我有一个对象数组而不是一个值数组:

{ "_id" : 1, "items" : [
    {x: "one", y: "two", z: "three"}, 
    {x: "four", y: "five", z: "six"},
    {etc...}
]}

例子给出如下例子:db.inventory.aggregate([{$project: {index: {$indexOfArray: [ "$items", 2 ] }}}]

2 是要在 $items 的数组表达式中查找的搜索表达式。

我的问题是因为我试图找到元素 y 等于 myVariableValue 的对象的索引。一直在尝试许多不同的组合来重新排列语法,但没有 return 除了 -1 之外的任何东西,这意味着它没有找到。

db.collection.aggregate([
    {$match: {_id: id}},
    {$project: {index: {$indexOfArray: [ "$items", {y: myVariableValue} ] }}}
]);

似乎行不通,但我认为肯定行得通。

我正在寻找 return 索引正确值的正确搜索语法是什么?谢谢!

你的 $indexOfArray 语法必须是这样的:

  {
    $project: {
      index: {
        $indexOfArray: [
          "$items.y",
          myVariableValue
        ]
      }
    }
  }

Playground

如果 mongodb 文档中存在对象数组的示例,那就太好了。