aldinokemal

MongoDB - Update

Mar 27th, 2022 (edited)
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // update products set category = "food" where _id = 1
  2. db.products.updateOne({
  3.     _id: 1
  4. },{
  5.     $set: {
  6.         category: "food"
  7.     }
  8. });
  9.  
  10. // update products set category = "food" where _id = 2
  11. db.products.updateOne({
  12.     _id: 2
  13. },{
  14.     $set: {
  15.         category: "food"
  16.     }
  17. });
  18.  
  19. // update products set tags = ["food"] where category = "food" and tags is null
  20. db.products.updateMany({
  21.     $and: [
  22.         {
  23.             category :{
  24.                 $eq: "food"
  25.             }
  26.         },
  27.         {
  28.             tags: {
  29.                 $exists: false
  30.             }
  31.         }
  32.     ]
  33. }, {
  34.     $set: {
  35.         tags: ["food"]
  36.     }
  37. })
  38.  
  39. // update products set wrong = "wrong"
  40. db.products.updateMany({}, [
  41.     {
  42.         $set: {
  43.             wrong: "wrong"
  44.         }
  45.     }
  46. ]);
  47.  
  48. // update products set wrong = null
  49. db.products.updateMany({}, [
  50.     {
  51.         $set: {
  52.             wrong: null
  53.         }
  54.     }
  55. ]);
  56. db.products.updateMany({}, [
  57.     {
  58.         $unset: [ "wrong" ]
  59.     }
  60. ]);
  61.  
  62. // insert wrong document
  63. db.products.insertMany([
  64.     {
  65.         _id: 9,
  66.         name: "Ups Salah",
  67.         wrong: "Salah Lagi"
  68.     }
  69. ]);
  70.  
  71. // replace document with id 9
  72. db.products.replaceOne({
  73.     _id: 9
  74. }, {
  75.     name: "Adidas Pulseboost HD Running Shoes Sepatu lari Pria",
  76.     price: new NumberLong('1100000'),
  77.     category: "shoes",
  78.     tags: [
  79.         "adidas", "shoes", "running"
  80.     ]
  81. });
Add Comment
Please, Sign In to add comment