MongoDB - Querying Arrays
Create an collection by name employe1 that contains the course array
db.employee1.insert({name:"satish",courses:["dbms","java","python","c"]})
db.employee1.insert({name:"ram",courses:["java","mongodb"]})
Display employees who teach java from the employee1 collection
db.employee1.find({courses:"java"})
Display all the employees who do not teach mongodb
db.employee1.find({courses:{$nin:["mongodb"]}})
Display only employees who teach java and python
db.employee1.find({courses:{$in:["mongodb","java"]}})
Display all employees who teach only 2 courses
db.employee1.find({courses:{$size:2}})
Display all employees teaching java and mongodb
db.employee1.find({courses:["java","mongodb"]})
Display employees teaching java and mongodb irrespective of the order
db.employee1.find({courses:{$all:["mongodb","java"]}})
Create a student collection with marks array and perform the following
Find all the students whose marks is [25,35,45,12,9]
db.student.find({marks:[25,35,45,12,9]})
Display the first three marks of all students
db.student.find({},{marks:{$slice:3}})
Display the first element in the array
db.student.find({},{marks:{$slice:1},_id:0,name:0})
Display the last element in the array
db.student.find({},{marks:{$slice:-1},_id:0,name:0})
Display the first mark scored by student named jeff
db.student.find({name:"jeff"},{marks:{$slice:1},_id:0,name:1})
Display student who has only three subjects
db.student.find({marks:{$size:3}})
Display student who scored more than 50 marks in atleast one subject
db.student.find({marks:{$elemMatch:{$gt:50}}})
Display Students who have scored mark greater than 89 and less than 95 in at least one subject.
db.student.find({marks:{$elemMatch:{$gt:89,$lt:97}}})
Display all the students who have scored greater than 10 marks in at least one subject in exam1
db.student1.find({"marks.exam1":{$gt:10}})
Display the student who has scored the following marks in exam1 : [ 1, 2, 3, 4 ]
db.student1.find({"marks.exam1":[ 1, 2, 3, 4 ]})
Display the student who as scored 33 marks in the first subject in exam 2
db.student1.find({"marks.exam2":{$eq:33}})