Save for later
CRUD Operations
in MongoDB
@nacercodes
001
Insert One
db.collection.insertOne(document)
db.languages.insertOne({
name: 'Python',
createdBy: 'Guido van Rossum',
appearedIn: 1991,
isNew: false
})
Inserts one document with “Python” details into
languages collection.
@nacercodes
002
Insert Many
db.collection.insertMany([
document1,
document2,
...
])
db.languages.insertMany([
{ name: 'Python' },
{ name: 'JavaScript' }
])
Inserts multiple documents into the same collection all
at once.
@nacercodes
003
Find One
db.collection.findOne(query, projection)
db.languages.findOne(
{ name: 'Python' },
{ createdBy: 1 }
Gets only the _id (included by default) and
createdBy fields of the first document that satisfies
the search criteria (name equals “Python”).
@nacercodes
004
Find
db.collection.find(query, projection)
db.languages.find(
{ appearedIn: { $gt: 1990 } },
{ name: 1 }
Gets only the _id and name fields of all the documents
that satisfy the search criteria (appearedIn greater
than “1990”).
Calling find() with no arguments will return all the
documents.
@nacercodes
005
Update One
db.collection.updateOne(filter, update)
db.languages.updateOne(
{ name: 'Go' },
{ $set: { name: 'Golang' } }
Updates the name field to “Golang” of the first
document that matches the filter (name equals “Go”).
@nacercodes
006
Update Many
db.collection.updateMany(filter, update)
db.languages.updateMany(
{ appearedIn: { $lt: 2010 } },
{ $set: { isNew: false } }
Updates the isNew field to “false” of all the documents
that match the filter (appearedIn less than “2010”).
@nacercodes
007
Delete One
db.collection.deleteOne(filter)
db.languages.deleteOne({
name: 'Visual Basic'
})
Removes the first document that matches the filter
(name equals “Visual Basic”).
@nacercodes
008
Delete Many
db.collection.deleteMany(filter)
db.languages.deleteMany({
appearedIn: { $gt: 2022 }
})
Removes all the documents that match the filter
(appearedIn greater than “2022”).
@nacercodes
Nacer Codes
@nacercodes
Save it or lose it. ️
s
de
rco
ce
na