Home > Blockchain >  Referencing a list during a MongoDB aggregation
Referencing a list during a MongoDB aggregation

Time:10-08

I have a list of musical keys:

keys = ["C", "C♯/D♭", "D" , "D♯/E♭", "E", "F", "F♯/G♭", "G", "G♯/A♭", "A", "A♯/B♭", "B"]

And an aggregation pipeline:

songsPipeline =[
    { "$match" : { "userName": "stevendiffey" } },
    { "$unwind" : "$songs"},
    { "$project" : { "_id" : 0,
        "song" : "$songs.song",
        "artist" : "$songs.artist",
        "spotifyURI" : "$songs.spotifyURI",
        "image" : "$songs.image",
        "uuid" : "$songs.uuid",
        "key" : "$songs.key"},
        }
    ]

How do I set key in the output to a key in the keys list?

I realised that key was outputting as a string, so I set it to an integer with:

{
    "$set": { "key": { "$toInt": "$key" }}
}

Natuarally I then thought that I could do:

{
    "$set": { "key": keys["key"] }
}

But that returns: TypeError: list indices must be integers or slices, not str

How best to set to the list?

Ideally, I want to keep it all within the pipeline, so that I can return it to a Jinja template.

CodePudding user response:

Use arrayElemAt. "key" field should look something like this.

"key" : {$arrayElemAt: [["C","C♯/D♭","D","D♯/E♭","E","F","F♯/G♭","G","G♯/A♭","A","A♯/B♭","B"], {$toInt: "$songs.key"}]}
  • Related