0% found this document useful (0 votes)
22 views6 pages

MongoDB Operations and Queries Guide

Uploaded by

pranay23varanasi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views6 pages

MongoDB Operations and Queries Guide

Uploaded by

pranay23varanasi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unstructured Databases Lab Manual

Course Code: 22CS11S7

1.a. Execute the Commands of MongoDB and operations in MongoDB Insert, Update
Delete and Projection. (Note: use any collection).
b Illustration of Where Clause, AND, OR operations in MongoDB.

To create a collection in MongoDB, you can use either:

1. MongoDB Shell / Command Line (mongosh)


2. MongoDB Compass (GUI)
3. Using Code (e.g., Python, [Link], etc.)

use schoolDB; // Switch to (or create) the database

[Link]("student"); // Create the collection

[Link]({
name: "Rithvik Madugula",
age: 21,
course: "Computer Science",
grade: "A"
});

1. Insert Operations
[Link]({
name: "Rithvik Madugula",
age: 21,
course: "Computer Science",
grade: "A"
});

Insert Many Students


[Link]([
{ name: "Anika Sharma", age: 22, course: "IT", grade: "B" },
{ name: "Rahul Verma", age: 20, course: "ECE", grade: "A" },
{ name: "Sneha Rao", age: 23, course: "CSE", grade: "C" }
]);

2. Update Operations
Update One Student’s Grade
[Link](
{ name: "Rahul Verma" },
{ $set: { grade: "A+" } }
);
Update All Students from CSE to AI&DS
[Link](
{ course: "CSE" },
{ $set: { course: "AI&DS" } }
);

3. Delete Operations

Delete One Student


[Link]({ name: "Sneha Rao" });

Delete All Students with Grade "C"


[Link]({ grade: "C" });

4. Projection (Select Specific Fields)

Display Only Name and Course of All Students


[Link]({}, { name: 1, course: 1, _id: 0 });

Display Students with Grade "A" and show only Name and Grade
[Link](
{ grade: "A" },
{ name: 1, grade: 1, _id: 0 }
);

2 a. Develop a MongoDB query to select certain fields and ignore some fields of the
documents from any collection.
b. Develop a MongoDB query to display the first 5 documents from the results obtained.

a)In MongoDB, to select certain fields and ignore others, you use the projection parameter in the
find() query.

Syntax:
[Link](query, projection)

Example 1: Select only name and course, ignore _id


[Link]({}, { name: 1, course: 1, _id: 0 });

Example 2: Ignore age and grade, show everything else


[Link]({}, { age: 0, grade: 0 });

Example 3: Show only name and grade, hide _id


[Link]({}, { name: 1, grade: 1, _id: 0 });

b) To display the first 5 documents from a MongoDB query result, you use the .limit()
method after the find() operation.
Basic Query: Display First 5 Documents
[Link]().limit(5);

This will return the first 5 documents from the student collection.

With Projection: Only name and course fields


[Link]({}, { name: 1, course: 1, _id: 0 }).limit(5);

3a. Execute query selectors (comparison selectors, logical selectors) and list out the
results on any collection
b. Execute query selectors (Geospatial selectors, Bitwise selectors) and list out the
results on any collection

a. {
"_id": 1,
"name": "Alice",
"age": 22,
"grade": 85,
"department": "CSE"
}
{
"_id": 2,
"name": "Bob",
"age": 21,
"grade": 74,
"department": "ECE"
}
{
"_id": 3,
"name": "Charlie",
"age": 23,
"grade": 91,
"department": "CSE"
}
{
"_id": 4,
"name": "David",
"age": 20,
"grade": 67,
"department": "IT"
}

Examples
1. Find students with grade greater than 80

[Link]({ grade: { $gt: 80 } })

2. Find students in departments CSE or ECE

[Link]({ department: { $in: ["CSE", "ECE"] } })

[Link] students who are in CSE and have grade > 80


[Link]({
$and: [
{ department: "CSE" },
{ grade: { $gt: 80 } }
]
})

[Link] students who are either in IT or have a grade less than 70

[Link]({
$or: [
{ department: "IT" },
{ grade: { $lt: 70 } }
]
})

5. Find students not in the CSE department


[Link]({
department: { $ne: "CSE" }
})

b. Execute query selectors (Geospatial selectors, Bitwise selectors) and list out the
results on any collection

Geospatial Selectors
{
"_id": 1,
"name": "Library",
"location": { "type": "Point", "coordinates": [77.5946, 12.9716] }
}
{
"_id": 2,
"name": "Cafeteria",
"location": { "type": "Point", "coordinates": [77.5950, 12.9720] }
}
{
"_id": 3,
"name": "Sports Complex",
"location": { "type": "Point", "coordinates": [77.5800, 12.9500] }
}
[Link]({ location: "2dsphere" })

1. Find places near a point (e.g., within 1000 meters of a coordinate)


[Link]({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [77.5946, 12.9716]
},
$maxDistance: 1000
}
}
})

2. Find places within a polygon area


[Link]({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[
[77.5930, 12.9700],
[77.5960, 12.9700],
[77.5960, 12.9730],
[77.5930, 12.9730],
[77.5930, 12.9700]
]]
}
}
}
})

2 Bitwise Selectors
{
"_id": 1,
"device": "Sensor A",
"status": 5 // Binary: 0101
}
{
"_id": 2,
"device": "Sensor B",
"status": 6 // Binary: 0110
}
{
"_id": 3,
"device": "Sensor C",
"status": 3 // Binary: 0011
}
1. Match documents where bit 1 (from right) is set (010 → bit 1 = 1)
[Link]({
status: { $bitsAllSet: 2 }
})

2. Match documents where any of the bits 1 or 2 is set


[Link]({
status: { $bitsAnySet: 6 } // Binary 110
})
3. Match documents where none of bits 1 and 2 are set
[Link]({
status: { $bitsAllClear: 6 }
})

Common questions

Powered by AI

To find students majoring in either CSE or ECE, use the `$in` logical operator, which checks for any matching value in the specified array. The query would be `db.students.find({ department: { $in: ['CSE', 'ECE'] } })`. This query filters documents where the `department` field value matches either 'CSE' or 'ECE' .

The `$near` operator in MongoDB is used to find documents with geospatial data close to a specified location. To use `$near`, we first ensure the geospatial data has been indexed using the `2dsphere` index. An example query is `db.places.find({ location: { $near: { $geometry: { type: 'Point', coordinates: [77.5946, 12.9716] }, $maxDistance: 1000 } } })`, which identifies places within 1000 meters of a given coordinate. Using `$near` helps in applications like finding nearby amenities or services based on user location .

In MongoDB, insert operations are performed using `insertOne()` to add a single document, such as `db.student.insertOne({ name: 'Rithvik Madugula', age: 21, course: 'Computer Science', grade: 'A' })`, and `insertMany()` to add multiple documents simultaneously. For updates, `updateOne()` and `updateMany()` are used to modify specific documents based on query conditions, exemplified by `db.student.updateOne({ name: 'Rahul Verma' }, { $set: { grade: 'A+' } })`, which updates one student's grade. Deletion operations employ `deleteOne()` and `deleteMany()` methods, such as `db.student.deleteOne({ name: 'Sneha Rao' })` to remove individual documents, and `deleteMany()` for batch deletions .

In MongoDB, projection allows the inclusion or exclusion of specific fields in the query results, without returning the entire document. Projection is specified in the `find()` method as a second parameter. For example, `db.student.find({}, { name: 1, course: 1, _id: 0 })` selects only the `name` and `course` fields, excluding the `_id`. Similarly, `db.student.find({}, { age: 0, grade: 0 })` returns all fields except `age` and `grade`. This is useful for obtaining only relevant data, minimizing data transfer and processing costs .

MongoDB geospatial queries use spatial data to find documents based on their location. Documents must include fields with geometric data types. For example, the query `db.places.find({ location: { $geoWithin: { $geometry: { type: 'Polygon', coordinates: [[[77.5930, 12.9700], [77.5960, 12.9700], [77.5960, 12.9730], [77.5930, 12.9730], [77.5930, 12.9700]]] } } } })` finds documents within a specified polygon area. Another example with `$near` finds locations close to a given point: `db.places.find({ location: { $near: { $geometry: { type: 'Point', coordinates: [77.5946, 12.9716] }, $maxDistance: 1000 } } })`, identifying documents within 1000 meters of a specified coordinate .

The `$set` operator in MongoDB is used to update fields of a document. When applied, it sets the value of a field to a specified value, or adds the field if it doesn't exist. For example, `db.student.updateOne( { name: 'Rahul Verma' }, { $set: { grade: 'A+' } } )` upgrades Rahul Verma's grade to 'A+'. To update a field across multiple documents, such as changing all CSE students' courses to AI&DS, use `updateMany()`: `db.student.updateMany( { course: 'CSE' }, { $set: { course: 'AI&DS' } } )`. This command applies the update to every document where the condition is met .

The `$geoWithin` operator in MongoDB identifies documents that exist within a specified geographical area. Used with `$geometry`, it checks if an object's location lies within a defined shape, such as a polygon. For example, `db.places.find({ location: { $geoWithin: { $geometry: { type: 'Polygon', coordinates: [[[77.5930, 12.9700], [77.5960, 12.9700], [77.5960, 12.9730], [77.5930, 12.9730], [77.5930, 12.9700]]] } } } })` fetches places within the specified polygon. This operation is applicable in mapping applications to find points of interest within a user-defined area, such as finding all stores within a city block .

Bitwise selectors in MongoDB allow filtering of documents based on the binary representation of field values. The `$bitsAllSet` operator checks if all specified bits are set in a field; for example, `db.devices.find({ status: { $bitsAllSet: 2 } })` matches documents where the binary representation of `status` has bit 1 set. The `$bitsAnySet` operator returns documents where any of the bits specified are set, as seen in `db.devices.find({ status: { $bitsAnySet: 6 } })`, which matches any document with either bit 1 or 2 set. Conversely, `$bitsAllClear` returns documents where none of the specified bits are set .

Logical query selectors such as `$and` and `$or` in MongoDB enable the formation of complex query conditions by combining multiple criteria. The `$and` operator is used to specify conditions that all must be met; for instance, to find CSE students with a grade greater than 80, use `db.students.find({ $and: [{ department: 'CSE' }, { grade: { $gt: 80 } }] })`. The `$or` operator allows any of the criteria to be satisfied, such as `db.students.find({ $or: [{ department: 'IT' }, { grade: { $lt: 70 } }] })`, which finds students either in the IT department or with a grade less than 70 .

In MongoDB, you can limit the number of documents returned by using the `.limit()` method chain after a `find()` query. To apply projection and limit the results simultaneously, include a projection specification within the `find()` method, and then apply `.limit(n)`. For example, to return only the first 5 documents showing the `name` and `course` fields, the query would be `db.student.find({}, { name: 1, course: 1, _id: 0 }).limit(5)` .

You might also like