Setting a new property in a document based on elements of another array property

I have a collection of documents whose schema contains an array property (e.g., let’s call it keys) that holds an array of strings.
However, I have since realized that this array is only ever going to contain 1 string or be empty, so I want to update all the documents in my collection such that instead of having an array property called ‘keys’, each one will have a string property called key that either has the value of keys[0] if keys[] contained an element, or undefined if keys[] was empty, and then I want to delete the keys property.

I know that I can use the $unset operator to get rid of the keys property at the end. My question is: for the part about setting a new property called key based on what keys contains – how do I specify it when using the $set operator?
I want to do something like the following:

  myCollection.updateMany({}, [
    { $set: { key: "keys.0" ? "keys.0" : undefined } },

and I am aware that the above syntax is of course wrong. What is the right syntax for this operation?

Just to close the issue, thanks to a tip from a colleague, I was able to do the following:

await myCollection.updateMany({ keys: { $size: 1 } }, [
   { $set: { key: { $first: "$keys" } } },
await myCollection.updateMany({}, [{ $unset: "keys" }]);
1 Like