Wednesday, October 15, 2014

MongoDB CRUD


Create/Insert

> db.Employee.insert({Name:"Supreet",Empid:199380,Designation:"Associate Consultant"})
WriteResult({ "nInserted" : 1 })
> db.Employee.insert({Name:"Tom",Empid:199381,Designation:"Project Engineer"})
WriteResult({ "nInserted" : 1 })

Select All documents

> db.Employee.find()
{
"_id" : ObjectId("540d4a2a4069474f1248f63f"),
"Empid" : 199380,
"Name" : "Supreet",
"Designation" : "Associate Consultant"
}
{
"_id" : ObjectId("540d4a654069474f1248f64b"),
"Empid" : 199381,
"Name" : "Tom",
"Designation" : "Project Engineer"
}

Update a document

> db.Employee.update({Empid:199381},{$set:{Designation:"Technical Lead"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })


> db.Employee.find()
{
"_id" : ObjectId("540d4a2a4069474f1248f63f"),
"Empid" : 199380,
"Name" : "Supreet",
"Designation" : "Associate Consultant"
}
{
"_id" : ObjectId("540d4a654069474f1248f64b"),
"Empid" : 199381,
"Name" : "Tom",
"Designation" : "Technical Lead"
}


remove a document


> db.Employee.remove({Empid:199381})
WriteResult({ "nRemoved" : 1 })
> db.Employee.find()
{
"_id" : ObjectId("540d4a2a4069474f1248f63f"),
"Empid" : 199380,
"Name" : "Supreet",
"Designation" : "Associate Consultant"
}
show all collections(tables) in the database

> show collections
Employee

using OR operator

> db.Employee.find({$or:[{Empid:199380},{Name:"Supreet"}]})
{
"_id" : ObjectId("540d4a2a4069474f1248f63f"),
"Empid" : 199380,
"Name" : "Supreet",
"Designation" : "Associate Consultant"
}

Using Greater than operator

> db.Employee.find({ Empid:{$gt:199379}})
{
"_id" : ObjectId("540d4a2a4069474f1248f63f"),
"Empid" : 199380,
"Name" : "Supreet",
"Designation" : "Associate Consultant"
}

db.products.find({"Price":{$gt:20000}})
/* 0 */
{
    "_id" : ObjectId("55923c10f7928010b0bd8a81"),
    "Name" : "Ego",
    "Category" : "Laptops",
    "Price" : 50000
}

/* 1 */
{
    "_id" : ObjectId("55923c3ef7928010b0bd8a82"),
    "Name" : "Sony1",
    "Category" : "Laptops",
    "Price" : 60000
}

No comments:

Post a Comment