How do I project the $type of a specific array-nested field in MongoDB?

Viewed 43

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.

1 Answers

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

Related