首页 > 解决方案 > MongoDB: Aggregate the index value in array of objects with element value of 'x'

问题描述

I'm trying to work from this part of the documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfArray/

and my use case is almost identical except instead of having an array of values I have an array of objects:

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

The example give the following example: db.inventory.aggregate([{$project: {index: {$indexOfArray: [ "$items", 2 ] }}}]

The 2 being the search expression to find withing the array expression of $items.

My problem is because I am trying to find the index of the object where element y equals myVariableValue. Been trying many different combinations rearranging the syntax but haven't had return anything except -1 which means it was not found.

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

Doesn't seem to work and thought it definitely would.

What is the correct search syntax I am looking for to return the correct value of the index? Thanks!

标签: mongodbaggregation-frameworkindexof

解决方案


Your $indexOfArray syntax must be like this:

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

Playground

It would be good, if an example existed for an array of objects in the mongodb docs.


推荐阅读