2

I want to determine the data type of a field that lives multiple arrays deep, at specific indexes.

For example, say I have a structure like so:

{ series: [
    {
        metaData: [
            { reference: "1" },
            { reference: 2 }
        ]
    }, {
        metaData: [
            { reference: 3.0 },
            { reference: [4] }
        ]
    }
]}

I want to project the $type of reference at a known pair of indexes, for example series index 1 and metaData index 0, which in the above case be a double. Essentially, I want this as my projection:

{ 'type': { '$type' : '$series.1.metaData.0.reference' }}

And returning something like this:

{ '_id': '12345', 'type': 'double' }

However, I can see from this section of the documentation that this doesn't work, and that I need to use some combination of $elemMatch, $slice, and $.

I just can't wrap my head around how to implement these in a nested manner.

0

1 Answer 1

1

There is no straight way to access element from nested array, you can try below approach if you really want to,

  • $arrayElemAt to get specific element from provided array and index number, so here we have used nested $arrayElemAt operator to reach reference field's value
  • $type to get datatype of the value
db.collection.aggregate([
  {
    $project: {
      type: {
        $type: {
          $arrayElemAt: [
            {
              $arrayElemAt: [
                "$series.metaData.reference",
                1 // <= index for "series" field
              ]
            },
            0 // <= index for "metaData" field
          ]
        }
      }
    }
  }
])

Playground

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.