Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

1.

Create a collection adding first document


We start by creating a database first .
use participanti
db.student.insert(
{
studno: 1,
fname: Eugen,
lname: Morar,
age: 32,
email: eugen28@yahoo.com
}
)
add 10 more

2.Viewing all records from a collection


It is simplest of all & most frequently used query. Just type
db.student.find()
db.student.find().sort({age: 1})

3.Viewing selected documents from a collection


If there are a huge number of documents in a collection and we do not want all fill our display screen.
db.student.find({fname: Eugen})
db.student.find({fname: Eugen, lname: Morar})
db.student.find({ $or: [{fname: Eugen}, {fname: Dan}]})
db.student.find({fname: /^E/})
db.student.find({age: {$ne:30}})
db.student.find({age: {$gte:30}})

4.Viewing selected keys from a collection


If there are a huge number of keys and we do not want all to fill our display screen.
db.student.find({}, {studno: 1, fname: 1, sname: 1})

db.student.find({}, {studno: 1, fname: 1, sname: 1, _id: 0})

5.Functions
Functions listing counts, distincts or execution plans for queries.
db.student.find().count()
db.student.find({email: {$exists: true}}).count()
db.student.find({age: {$gte: 30}}).count()
db.student.distinct(fname)
db.student.find().limit(3)
db.student.find({fname: Eugen}).explain()

6.Deleting documents from a collection


To delete the selected documents, just fire the following query:
db.student.remove({fname: Eugen})
db.student.remove({age: {$gte:30}})

7.Changing data in existing documents


Suppose we want to change the age of a student named Eugen in our table. We would fire this query:
db.student.update({fname: Eugen}, {$set: {age: 22}})
db.student.update({fname: Dan}, {$inc: {age: 15}}, {multi: true})

8.Delete the collection


Delete de collection and the database.
db.student.drop()
db.dropDatabase()

You might also like