Group B
Assignment No: 10
Class: T.E. Computer Roll No:
Aim: Develop MongoDB Queries using SAVE & Logical Operators.
Problem Statement:
Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations,
SAVE method, logical operators)
Objective:
1. To learn and understand NOSQL Databas..
2. To execute CRUD Operations using SAVE Method & Logical Operators.
Hardware requirements:
Any CPU with Pentium Processor or similar, 256 MB
RAM or more, 1 GB Hard Disk or more.
Software requirements:
Ubuntu 14.04, MongoDB Packages.
Theory:
MongoDB Save() Method
he db.collection.save() method is used to updates an existing document or inserts a new document,
depending on its document parameter.
Syntax
The basic syntax of MongoDB save() method is shown below −
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Example
Following example will replace the document with the _id '5983548781331adf45ec7'.
>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Test1",
"by":"JIT"
}
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New Topic",
"by":"DBMSTutor"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Test1",”by” : ”JIT”}
>
save()method performs an insert since the document passed to the method does not contain
the_idfield. During the insert, the shell will create the _id field with a unique ObjectId value, as
verified by the inserted document.
save()performs an update withupsert:true since the document contains an_idfield.
e.g. db.invoice.save( { _id: 1001,inv_no: "I00001", inv_date: "10/10/2012", ord_qty:200 } );
Logical Oerators in MongoDB:
Name Description
$and Joins query clauses with a logical AND returns all documents that match the conditions of
both clauses.
$not Inverts the effect of a query expression and returns documents that do not match the query
expression.
$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
$or Joins query clauses with a logical OR returns all documents that match the conditions of
either clause
e.g.
1)AND Queries With Multiple Expressions Specifying the Same Field
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )
This query will select all documents in the inventory collection where:
the price field value is not equal to 1.99 and
the price field exists.
2)AND Queries With Multiple Expressions Specifying the Same Operator
db.inventory.find( {
$and : [
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
})
This query will select all documents where:
the price field value equals 0.99 or 1.99, and
the sale field value is equal to true or the qty field value is less than 20
Conclusion: