mongodb - How to return array index with $indexOfArray -
i have following document structure in mongo:
{ "participantidentities": [ { "player": { "summonername": "summ1", "otherdata": "whatever" }, "participantid": 1 }, { "player": { "summonername": "summ2", "otherdata": "whatever2" }, "participantid": 2 } ] } and trying return index of 1 of elements, can pass next part of pipeline it's throwing error.
code:
db.match.aggregate( [ { "$project": { "matchedindex": { "$indexofarray": [ "$participantidentities", {"$player.summonername": {$eq: "summ2"}} ] } } } ] ) error:
"ok" : 0, "errmsg" : "unrecognized expression '$participantidentities.player.summonername'", "code" : 168, "codename" : "invalidpipelineoperator" i'm not sure i'm doing wrong, i'm not sure if querying current array's elements supported might issue?
in example above, i'd want return second element's array index (where summonername summ2) i.e. {"matchedindex": 1}. doing wrong?
if look @ usage tells you. "array" first argument , second argument "search expression" must produce value equality check.
so rather write expression "test element equality" instead "point element in array test". means notating "$participantidentities.player.summonername" in order test against "name" properties converted array:
db.match.aggregate([ { "$project": { "matchedindex": { "$indexofarray": [ "$participantidentities.player.summonername", "summ2" ] } }} ]) the notation takes source array , makes appear follows comparison:
[ "summ1", "summ2" ] or if prefer, think of above javascript equivalent idiom, using .map() , indexof()
participantidentities.map( p => p.player.summonername ).indexof("summ2") which same thing practical standpoint.
"$participantidentities.player.summonername" is "shorthand" using $map operator of mongodb.
and in comparison, since "second index" n-1 or 1 match, value returned.
Comments
Post a Comment