Alternative of indexOfArray for DocumentDB

Hi there,

I have a successfully working aggregation pipeline for Mongo like:

Data:

    {
    id: 1234,
    verbatim: clean
    numeric: 4
    },
    {
    id: 1234,
    verbatim: dirt
    numeric: 1
    },

Aggregation:

    {$group: {id: $id, 
                   status: {
                     "$push": {
                        "verbatim": "$verbatim",
                        "numeric": "$numeric"
                   }
            }}}

Projection:

    {status: {
                "$arrayElemAt": [
                    status.verbatim",
                    {
                        "$indexOfArray": [
                            "$status.numeric",
                            {"$max": "$status.numeric"}
                        ]
                    }
                ]
            }

This works fine with mongo, but does not with AWS DocumentDB because operator $indexOfArray is not supported.
How do I find an alternative way to find a verbatim field corresponding to maximal numeric?

Hello @AlexG, welcome to the community.

Here is a way. The following can be substituted:

"$indexOfArray": [
    "$status.numeric",
    { "$max": "$status.numeric" }
]

with:

$reduce: {
	input: { $range: [ 0, { $subtract: [ { $size: "$status.numeric" }, 1 ] } ] },
	initialValue: 0,
	in: {
		$cond: { if: { $eq: [ { $max: "$status.numeric"}, { $arrayElemAt: [ "$status.numeric", "$$this" ] } ] },
			     then: "$$this",
		         else: "$$value"
				}
	}
}

Hi @Prasad_Saya,
thanks for the quick reply.
Unfortunately, $reduce is also not implemented in AWS DocumentDB :frowning:

Hi @AlexG,

Amazon DocumentDB is a separate implementation from the MongoDB server. DocumentDB uses the MongoDB 3.6 wire protocol, but there are number of functional differences and the supported commands are a subset of those available in MongoDB 3.6 (and earlier). For example, the $indexOfArray and $reduce aggregation operators were introduced in MongoDB 3.4.

If the server-side operators you’d like to use aren’t available in DocumentDB, the likely workaround will be manipulating results or documents in your application code.

If you want to use a managed MongoDB service on AWS, MongoDB Atlas builds on MongoDB Enterprise server and does not require compatibility workarounds.

Regards,
Stennie

1 Like