Advertisement
nodejsdeveloperskh

Add or update field with random numbers ($merge, $rand, $floor, $set)

Dec 21st, 2021
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. db.getCollection('collection-name').aggregate([
  2.     {
  3.         $match: { _id: ObjectId("60c08f97f4738c0018701eb9") }
  4.         // other conditions ...
  5.     },
  6.     {
  7.         $set: {
  8.             // MongoDB will creates this field if there is not
  9.             fieldName: {
  10.                 // this operators will generate random numbers from 0 to 20 for this field
  11.                 $floor: {
  12.                     $multiply: [ { $rand: {} }, 20 ]
  13.                 }
  14.             }
  15.         }
  16.     },
  17.     {
  18.         $merge: {
  19.             into: 'contractors',
  20.             on: '_id',
  21.             whenMatched: 'merge',
  22.         }
  23.     }
  24. ])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement