Home > OS >  Indexes of Elements in Array
Indexes of Elements in Array

Time:12-10

I have a collection with the following document

{
  "_id" : ObjectId("4e8ae86d08101908e1000001"),
  "food" : ["Apples", "Banana", "Grapes", "Pear"],
}

How do I construct an aggregation that will return the indexes of elements matching an array i.e

Suppose

array = ["Apples", "Grapes"]

How do I get the following

indexes: [0, 2]

I know that $indexOfArray returns the index of the first occurrence of an element matching the search expression, but is there a way to use it so that I can construct an array of indexes with it?

CodePudding user response:

  • $match
  • $unwind
  • $match
  • $group
db.collection.aggregate([
  {
    "$match": {
      "food": {
        $in: [
          "Apples",
          "Grapes"
        ]
      }
    }
  },
  {
    $unwind: {
      path: "$food",
      includeArrayIndex: "index"
    }
  },
  {
    "$match": {
      "food": {
        $in: [
          "Apples",
          "Grapes"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "index": {
        "$push": {
          "$toInt": "$$ROOT.index"
        }
      }
    }
  }
])

mongoplayground

  • Related