Full-stack Web Technologies

CHAPTER 2
CRUD Operations

Collection CRUD Methods

For one document only:

For many documents:

insertOne
db.users.insertOne({ username: 'jbond', age: 27 })
{
  "acknowledged": true,
  "insertedId": ObjectId("5ee9f09b6b327281a5213f43")
}
insertMany
db.users.insertMany([
  { username: 'zipi', age: 9 },
  { username: 'zape', age: 9 }
])
{
  "acknowledged": true,
  "insertedIds": [
    ObjectId("5ee9fa446b327281a5213f44"),
    ObjectId("5ee9fa446b327281a5213f45")
  ]
}
updateOne

By ID:

db.users.updateOne({ _id: ObjectId("5ee9fa446b327281a5213f44") }, {
  $set: { name: 'Zipi' }
})
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }

By filter:

db.users.updateOne({ username: 'zipi' }, {
  $set: { isBad: true }
})
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
updateMany
db.users.updateMany({
  age: { $lt: 10 },
}, {
  $set: { isChild: true }
})
{ "acknowledged": true, "matchedCount": 2, "modifiedCount": 2 }
deleteOne
db.users.deleteOne({ age: { $gt: 10 } })
{ "acknowledged": true, "deletedCount": 1 }
deleteMany
db.users.deleteMany({ isChild: true })
{ "acknowledged": true, "deletedCount": 2 }
replaceOne
db.users.replaceOne({ _id: ObjectId("5ee9fa446b327281a5213f44") }, {
  type: "Animal",
  sound: "Roarrr!"
})
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }