0

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?

1 Answer 1

1
  • $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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.