Updating a field with a random name from a list

I’ve udes this to update a field with a random number.

db.<collection>.updateMany({}, [{$set: {user_ID: {$floor: { $multiply: [{$rand: {}}, 10000]} } } }] )

How can I use this to update a field in all 10 documents with a random name from a list of 10 names?

e.g.
subjectNames = [ "Chemistry", "Physics", "Database Systems", "Functional Programming", . . ., "10th subject"]

In all 10 documents the field name is;
"Subject" : "subject_name"

Thanks in advance

1 Like

Hi,

Here is how you can do it:

  • $arrayElemAt - to access specific element of the array by index
  • $floor with $multiply and $rand - to generate random index from 0 to 4. In your case, you should add all the subjects in the array, and if there are 10 of them, you should multiply by 10 in the last step.
db.collection.aggregate([
  {
    "$set": {
      "subject": {
        "$arrayElemAt": [
          [
            "Chemistry",
            "Physics",
            "Database Systems",
            "Functional Programming",
            "Mathematics"
          ],
          {
            "$floor": {
              "$multiply": [
                {
                  "$rand": {}
                },
                5
              ]
            }
          }
        ]
      }
    }
  }
])

Working example

Thank you very much for this. Much appreciated

I forgot to say that “subject” should be “subjects” and it is an array of max 4. The list of subjects has 15 elements in them

subjectNames = [ "Chemistry", "Physics", "Database Systems", "Functional Programming", . . ., "10th subject"]

"subjects" : [ sub1, sub2, sub3, sub4 ]