1

I've got a document in MongoDB which has a multi-dimensional array as shown below.

{"_id":1,
     "name":"Johnson",
     "card":[
             ["",12,25,"","",52,60,"",86],
             [1,17,29,"",43,"","","",89],
             [3,"","",34,45,"",62,70,""]
           ]
    }

I'm looking for a query that returns the index of a particular element in the array, for example, say 29 whose index is [1][2] but when i queried as:

> db.test.aggregate([{$project:{index:{$indexOfArray:["$card",29]}}}])

i got the result as:

{ "_id" : 1, "index" : -1 }

which is not true. I found that this query method works only for one-dimensional array and I'm unable to figure out how to find the index of multi-dimensional array in MongoDB. Any help will be appreciated. Thankyou

1 Answer 1

2

Not exactly clear on what datatype [1][2] is, so rendering the desired output is a bit of a challenge. Here is a attempt to help your question...

Test Data

db.collection.insert(
{
    "name":"Johnson",
    "card":[
        ["", 12, 25, "", "", 52, 60, "", 86],
        [1, 17, 29, "", 43, "", "", "", 89],
        [3, "", "", 34, 45, "", 62, 70, ""]
    ]
}

(Assumes a hard-coded value of 29 to search for)

Aggregate

EDIT 2021-12-09 - ADDED $project TO CAST RESULTS AS INTEGER. WAS NumberLong()

db.collection.aggregate([
    {
        $unwind:
        {
            path: "$card",
            includeArrayIndex: "outerIndex"
        }
    },
    {
        $unwind:
        {
            path: "$card",
            includeArrayIndex: "innerIndex"
        }
    },
    {
        $match:
        {
            "card": 29
        }
    },
    {
        $project:
        {
            name: 1,
            card: 1,
            outerIndex: { $convert: { input: "$outerIndex", to: "int" } },
            innerIndex: { $convert: { input: "$innerIndex", to: "int" } }
        }
    }
])

Results

[
  {
    _id: ObjectId("61b13476c6c466d7d1ea9b5e"),
    name: 'Johnson',
    card: 29,
    outerIndex: 1,
    innerIndex: 2
  }
]

Unwanted fields can be supressed with another $project stage, but I did not include it here since I was not clear on desired output.

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

3 Comments

Thank you so much for your response. It worked. As to make clear, [1][2] is a Int32 datatype and output should be as outerIndex: 1, innerIndex: 2 instead of outerIndex: Long("1"), innerIndex: Long("2"). Please help me out.
@aemisom - I have modified my answer to include a $project to cast the NumberLong() as an ordinary int.
Thank you so much for your kindness. You are great.... God Bless You

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.