Advertisement
vvccs

ADS_6_CRUD_mongo

Oct 15th, 2024 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JSON 1.45 KB | None | 0 0
  1. EXP 6:
  2.  
  3. MONGODB CRUD
  4.  
  5. open cmd type mongosh // if not shows then no mongo is present
  6. use db;
  7.  
  8. //Create collection
  9. db.createCollection("emp");
  10. // 1. Create (Insert)
  11.  
  12. // Insert One Document
  13. db.collectionName.insertOne({
  14.     key1: "value1",
  15.     key2: "value2"
  16. });
  17.  
  18. // Insert Multiple Documents
  19. db.collectionName.insertMany([
  20.     { key1: "value1", key2: "value2" },
  21.     { key1: "value3", key2: "value4" }
  22. ]);
  23.  
  24. // 2. Read (Find)
  25.  
  26. // Find One Document
  27. db.collectionName.findOne({ key: "value" });
  28.  
  29. // Find All Documents
  30. db.collectionName.find({});
  31.  
  32. // Find with Query
  33. db.collectionName.find({ key: "value" });
  34.  
  35. // Find with Projection
  36. db.collectionName.find({ key: "value" }, { key1: 1, key2: 1 });
  37.  
  38. // Find with Sorting
  39. db.collectionName.find({}).sort({ key: 1 });
  40.  
  41. // Find with Limiting Results
  42. db.collectionName.find({}).limit(5);
  43.  
  44. // 3. Update
  45.  
  46. // Update One Document
  47. db.collectionName.updateOne(
  48.     { filterKey: "value" },
  49.     { $set: { keyToUpdate: "newValue" } }
  50. );
  51.  
  52. // Update Multiple Documents
  53. db.collectionName.updateMany(
  54.     { filterKey: "value" },
  55.     { $set: { keyToUpdate: "newValue" } }
  56. );
  57.  
  58. // Replace One Document
  59. db.collectionName.replaceOne(
  60.     { filterKey: "value" },
  61.     { newKey1: "newValue1", newKey2: "newValue2" }
  62. );
  63.  
  64. // 4. Delete
  65.  
  66. // Delete One Document
  67. db.collectionName.deleteOne({ filterKey: "value" });
  68.  
  69. // Delete Multiple Documents
  70. db.collectionName.deleteMany({ filterKey: "value" });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement