DEV Community

kishor sutradhar
kishor sutradhar

Posted on

Today’s new knowledge #1

web development

The first thing I do today is refresh my mongodb knowledge as it's an essential part of my Advanced Web Development course curriculum. and the key concepts i learned today are:

Simple CURD Operation on MongoDB

insert single document --> db.collection.insertOne();
insert multiple document --> db.collection.insertMeny();
find single document --> db.collection.findOne();
find multiple document --> db.collection.find();
update single document --> db.collection.updateOne();
update multiple document --> db.collection.updateMeny();
delete single document --> db.collection.deleteOne();
delete multiple document --> db.collection.deleteMany();

MongoDB Comparison Operators

MongoDB comparison operators allow you to filter documents by comparing field values.
$eq: Matches values that are equal to a specified value.
$ne: Matches values that are not equal to a specified value.
$gt: Matches values that are greater than a specified value.
$gte: Matches values that are greater than or equal to a specified value.
$lt: Matches values that are less than a specified value.
$lte: Matches values that are less than or equal to a specified value.
$in: Matches any of the values specified in an array.
$nin: Matches none of the values specified in an array.
Suppose we have a collection called users, with documents structured like this:

{ "_id": 1, "name": "Alice", "age": 25, "status": "A" }
{ "_id": 2, "name": "Bob", "age": 30, "status": "B" }
{ "_id": 3, "name": "Charlie", "age": 35, "status": "A" }
{ "_id": 4, "name": "David", "age": 28, "status": "C" }
{ "_id": 5, "name": "Eve", "age": 40, "status": "B" }
{ "_id": 6, "name": "Frank", "age": 22, "status": "A" }

Enter fullscreen mode Exit fullscreen mode

Now, let’s make a query that show each comparison operator.

//method one
db.users.find({
  $and: [
// Find documents where "age" is exactly 25
    { age: { $eq: 25 } },          
// and where "age" is NOT 30
    { age: { $ne: 30 } },           
// and where "age" is greater than 20
    { age: { $gt: 20 } },           
// and where "age" is 25 or higher
    { age: { $gte: 25 } },          
// and where "age" is less than 40
    { age: { $lt: 40 } },           
// and where "age" is 35 or lower
    { age: { $lte: 35 } },          
// and where "status" is either "A" or "B"
    { status: { $in: ["A", "B"] } }, 
// and where "status" is NOT "C" or "D"
    { status: { $nin: ["C", "D"] } } 
  ]
})

//method two
db.users.find({age: {$eq:25, $ne:30, $gt: 20, $gte: 25, $lt:40, $lte: 35}, status:{$in:["A", "B"], $nin:["C","D"]} })

//output:
{ "_id": 1, "name": "Alice", "age": 25, "status": "A" }


Enter fullscreen mode Exit fullscreen mode

method one is explicit and method
method two is inplicit and method

MongoDB’s logical operators

MongoDB’s logical operators allow you to combine and manipulate conditions within a query.

The $and operator in MongoDB allows you to combine multiple conditions in a single query.
The $or operator in MongoDB allows you to return documents that meet at least one of the conditions.
The $nor operator in MongoDB allows you to return documents that do not match the specified condition.
The $not operator in MongoDB Inverts the effect of a condition, returning documents that do not match the specified condition.

Now, let’s make a query that show each logical operator.

db.users.find({
  $and: [
    { $or: [{ status: "A" }, { age: { $lt: 25 } }] },
    { age: { $gt: 20 } },
    { age: { $not: { $gt: 35 } } },
    { $nor: [{ status: "B" }, { age: 30 }] }
  ]
})

//output
{ "_id": 1, "name": "Alice", "age": 24, "status": "A" }
{ "_id": 3, "name": "Charlie", "age": 28, "status": "A" }
{ "_id": 6, "name": "Frank", "age": 22, "status": "A" }

Enter fullscreen mode Exit fullscreen mode

MongoDB’s element operators

$exists: Checks if a field exists in the document.
$type: checks if the mensioned typed exits in the document.

Now, let’s make a query that show each logical operator.

 db.users.find({ "age": { $type: "int" } })
 db.users.find({ "status": { $exists: true } })

//output
[
{ "_id": 1, "name": "Alice", "age": 25, "status": "A" },
{ "_id": 2, "name": "Bob", "age": 30, "status": "B" },
{ "_id": 3, "name": "Charlie", "age": 35, "status": "A" },
{ "_id": 4, "name": "David", "age": 28, "status": "C" },
{ "_id": 5, "name": "Eve", "age": 40, "status": "B" },
{ "_id": 6, "name": "Frank", "age": 22, "status": "A" }
]
Enter fullscreen mode Exit fullscreen mode

MongoDB’s Array operators

$all: Matches arrays that contain all elements specified.
$elemMatch: Matches elements within an array based on specified criteria.
$size: Matches arrays with the specified number of elements.

Suppose we have a collection called students , with documents structured like this:

[
  { "_id": 1, "name": "Alice", "grades": [85, 90, 92], "subjects": ["Math", "English", "History"] },
  { "_id": 2, "name": "Bob", "grades": [78, 80, 85], "subjects": ["Math", "Science", "English"] },
  { "_id": 3, "name": "Charlie", "grades": [95, 98, 93], "subjects": ["Math", "History"] },
  { "_id": 4, "name": "David", "grades": [60, 70, 68], "subjects": ["Math", "Science"] }
]

Enter fullscreen mode Exit fullscreen mode

Now, let’s make a query that show each Array operator.

db.students.find({
  "grades": { $elemMatch: { $gt: 90 } }
})
//output 
[
  { "_id": 1, "name": "Alice", "grades": [85, 90, 92], "subjects": ["Math", "English", "History"] },
  { "_id": 3, "name": "Charlie", "grades": [95, 98, 93], "subjects": ["Math", "History"] }
]

db.students.find({
  "subjects": { $size: 3 }
})
//output 
[
  { "_id": 1, "name": "Alice", "grades": [85, 90, 92], "subjects": ["Math", "English", "History"] },
  { "_id": 2, "name": "Bob", "grades": [78, 80, 85], "subjects": ["Math", "Science", "English"] }
]

db.students.find({
  "subjects": { $all: ["Math", "History"] }
})
//output 
[
  { "_id": 1, "name": "Alice", "grades": [85, 90, 92], "subjects": ["Math", "English", "History"] },
  { "_id": 3, "name": "Charlie", "grades": [95, 98, 93], "subjects": ["Math", "History"] }
]
Enter fullscreen mode Exit fullscreen mode

Those operator are helpful in case of array and object filltering

MongoDB’s update operators

MongoDB provides several update operators that allow you to modify existing documents in a collection.
$set: Used to update the value of a field. If the field does not exist, it will be created.
$unset: Used to remove a field from a document.
$addToSet: Adds a value to an array only if the value does not already exist in the array (similar to a set).
$push: Adds a value to an array field. If the field does not exist, it will be created as an array.
$each: operator is used in conjunction with the $push and $addToSet operators to add multiple elements to an array field in a single update operation.
$pop: Removes the first or last element of an array.1 is used to remove last element and -1 is used to remove first element.
$pull: Removes all instances of a value from an array that match a specified condition.
$pullAll: operator is used to remove multiple specific values from an array field.
$rename: Renames a field in a document.

Now, let’s make a query that show each update operator.

db.students.updateOne(
  { "_id": 2 },{  $set: { "graduated": false } }
)

//output 
{ "_id": 2, "name": "Bob", "grades": [78, 80, 85], "subjects": ["Math", "Science", "English"], "graduated": false },

db.students.updateOne(
  { "_id": 2 }, { $unset: { "subjects": "" }}
)

//output
{ "_id": 2, "name": "Bob", "grades": [78, 80, 85], "graduated": false },

db.students.updateOne(
  { "_id": 2 }, { $addToSet: { "subjects": "Geography" }}
)

//output
{ "_id": 1, "name": "Alice", "grades": [85, 90, 92], "subjects": ["Math", "English", "History","Geography"] },

db.students.updateOne(
  { "_id": 1 }, { $push: { "grades": 88 }}
)

//output
{ "_id": 1, "name": "Alice", "grades": [85, 90, 92, 88], "subjects": ["Math", "English", "History","Geography"] }

db.students.updateOne(
  { "_id": 1 }, { $push: { "grades": { $each: [ 91, 82] }}}
)

//output
{ "_id": 1, "name": "Alice", "grades": [85, 90, 92, 88, 91, 82], "subjects": ["Math", "English", "History","Geography"] }

db.students.updateOne(
  { "_id": 1 },{  $pop: { "grades": 1 } // 1 for the last element, -1 for the first element }
)

//output
{ "_id": 1, "name": "Alice", "grades": [85, 90, 92, 88, 91], "subjects": ["Math", "English", "History","Geography"] }

db.students.updateOne(
  { "_id": 1 },{ $pull: { "grades": 90 }}
)

//output
{ "_id": 1, "name": "Alice", "grades": [85, 92, 88, 91], "subjects": ["Math", "English", "History","Geography"] }

db.students.updateOne(
  { "_id": 1 }, { $pullAll: { "grades": [80, 92] }}
)
//output
{ "_id": 1, "name": "Alice", "grades": [85, 88, 91], "subjects": ["Math", "English", "History","Geography"] }

db.students.updateOne(
  { "_id": 1 },{ $rename: { "name": "firstName" }}
)
//output
{ "_id": 1, "firstName": "Alice", "grades": [85, 88, 91], "subjects": ["Math", "English", "History","Geography"] }
Enter fullscreen mode Exit fullscreen mode

$set should be used for set premitive data
$addtoset should be used for not premitive data

Top comments (0)