Hi guys, does any one knows how can i add an element to an array whit a random value. I was trying using $rand in a push operator but it does not work
There is nothing special to do. Simply use the random number generate of your choice as the value. For example, in JS with Math.random() in mongosh.
db.test.insertOne( { _id:1 , myArray : [] })
{ acknowledged: true, insertedId: 1 }
db.test.find()
{ _id: 1, myArray: [] }
db.test.updateOne( { _id:1 } , { $push : { myArray : Math.random() }})
{ acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0 }
db.test.find()
{ _id: 1, myArray: [ 0.5932913987369441 ] }
2 Likes
Yesss. workss perfect, thankyou
Please mark my post as the solution so the thread can be closed and others know they can follow the suggestion.