Mongo DB#
MongoDB is a non-SQL database that stores data in JSON-like documents.
CRUD#
Consider the CURD operations in MongoDB. The following list show the collection methods (<database>.<collection>.<method>):
Insert data:
insertOne.insertMany.
The
findmethod to search data.Delete data:
deleteOne.deleteMany.
The following cell inserts document into the users collection:
mongosh --eval "db.users.insertOne({
name: 'Alice',
age: 30,
email: 'alice@example.com'
})" > /dev/null
The find method returns the created document:
mongosh --eval "db.users.find({})"
]0;mongosh mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000[
{
_id: ObjectId('68f774a651826e5330ce5f47'),
name: 'Alice',
age: 30,
email: 'alice@example.com'
}
]
The following cell uses the updateMany method to change the age attribute and displays the result.
mongosh --eval "db.users.updateMany(
{},
{ \$set: { age: 29 } }
)" > /dev/null
mongosh --eval "db.users.find({})"
]0;mongosh mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000[
{
_id: ObjectId('68f774a651826e5330ce5f47'),
name: 'Alice',
age: 29,
email: 'alice@example.com'
}
]
The following cell executes the deleteMany command with an empty condition; therefore, all documents in the corresponding collection will be deleted.
mongosh --eval "db.users.deleteMany({})" > /dev/null
The result of the find returns no documents.
mongosh --eval "db.users.find({})"
]0;mongosh mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000