11 SESION - MongoDB Commands and CRUD Operations I
11 SESION - MongoDB Commands and CRUD Operations I
Unstructured Data
• Log in | MongoDB
> db
• To switch databases, issue the use <db> helper, as in the following example:
• To create a new database, issue the use <db> command with the database
that you would like to create. Example
> db.myCollection.insertOne( { x: 1 } );
• If a collection does not exist, MongoDB creates the collection when you
first store data for that collection.
More Commands
>show collections
>cls
• Alternatively:
>console.clear()
More Commands
➢ <Ctrl + C>
• Or alternatively
>exit
CRUD Operations
CRUD Operations
db.grades.insertOne({
student_id: 654321,
products: [
{
type: "exam",
score: 90,
},
{
type: "homework",
score: 59,
},
{
type: "quiz",
score: 75,
},
{
type: "homework",
score: 88,
},
],
class_id: 550,
})
Insert Multiple Documents
db.grades.find()
Find a Document with Equality
• Example:
db.grades.find({ _id:ObjectId("651ccbab0023e1dfba073da8")
})
Find a Document with Equality
• Example:
• Example:
• Comparison operators:
• $gt
• $lt
• $lte
• $gte
The $gt Comparison Operator
• Example:
• Example:
• Example:
• Example:
db.grades.find({
products: {
$elemMatch: { type: "exam", score: { $gt: 60 }},
},
})
Finding Documents by Using Logical Operators
• Logical operators:
• implicit $and
• $or
• $and
Find a Document by Using Implicit $and
• Example:
• Example:
db.grades.find({
$or: [{"products.type": "quiz" }, {"product.score" : 70 }],
})
Find a Document by Using the $and Operator
db.grades.find({
$and: [
{ $or: [{"products.type" : "quiz" }, {"products.score" : 70}] },
{ $or: [{"class_id": 550 }, {"student_id" : 654321}] },
]
})
Next Session