MongoDB Query Language Essentials
MongoDB Query Language Essentials
The db.students.find() command with a projection differs by only displaying specified fields rather than all. Example: db.students.find({ department: 'CSE' }, { name: 1, _id: 0 }) will return only the name field without the _id field .
Use the $or logical operator to combine conditions: db.students.find({ $or: [ { age: 21 }, { department: 'IT' } ] }).
To update the age of the student named 'Arun' to 22, use the updateOne method: db.students.updateOne({ name: "Arun" }, { $set: { age: 22 } }).
To filter documents for students in the 'CSE' department, you can use the MongoDB find command with a specific filter: db.students.find({ department: "CSE" }).
To limit query results to two documents, use the limit method: db.students.find().limit(2).
Use db.students.insertMany to create multiple documents in a single operation. This is efficient for bulk inserts, saving network overhead and ensuring atomic insertion: db.students.insertMany([ { name: "Banu", age: 22, department: "ECE" }, { name: "Chitra", age: 23, department: "IT" } ]).
The aggregation framework provides tools for grouping and counting. To group by department and count students, use db.students.aggregate([ { $group: { _id: "$department", count: { $sum: 1 } } } ]).
To sort the students collection by age in ascending order, use db.students.find().sort({ age: 1 }).
To manually create a collection named 'students', use db.createCollection("students"). Manual creation may be necessary to specify options such as storage size, validation rules, or indexes. It provides control over collection properties that automatic creation during insert operations doesn’t offer .
To delete a single document, use deleteOne, which removes the first matched document: db.students.deleteOne({ name: "Banu" }). For multiple documents, use deleteMany, which removes all matched documents: db.students.deleteMany({ department: "IT" }).