1 of 43

Web Development Using Angular JS and MONGO

2 of 43

Unit 5

Document with different types of values i)Document with Scalar Values ii)Document with Documents as values iii)Document with Array as values CRUD operation :Insert Operation i)insertOne() and ii)insertMany() with examples Perform Query Operation for the following situations i)Query on nested documents ii)Query an array ii)Query an array of nested documents iv)Geospatial Queries Query Operation Examples Update Operation: updateOne(), updateMany() replaceOne(), findAndModify() Update operation :Examples

Lab :Working with CRUD operations

Insert and Query Delete Operation: deleteMany(), deleteOne() iii)findOneAndDelete() Delete operation Examples Operation on Mongodb Data: projection Limiting Records Sorting Records Indexes in Mongodb, default _id index Creating and Index createIndex method Single Field, Compound, Multikey Geospatial,text Index, Hashed Index

Lab :Working with CRUD operations

Update and Delete Properties of Index i)Unique Indexes ii)Partial Indexes iii)Sparse Indexes iv)TTL Indexes Aggregation in Mongodb: i)aggregate() method Aggregate expressions: i) $sum ii) $avg iii) $min iv) $max v) $push vi) $addToSet vii) $first viii) $last Mongodb Backup: Export/Import data backup using shell i)mongodump ii)mongorestore Mongodb Backup: Export/Import data backup using Mongo Compass Monitoring Deployment using Mongodb: i)mongostat, mongotop

iii)serverStatus, dbStats, collStats

Lab: i)Creating different types of indexes ii)Aggregate data using different Aggregate expressions iii)Perform Mongodb data Export and Import using shell as well as mongo compass. iv)Working with mongo deployment commands

3 of 43

Understanding MongoDB Documents

  • The document, which is comprised of field/value pairs, is at the heart of the MongoDB data structure. Most interactions with MongoDB occur at the document level.

  • MongoDB documents are composed of field-and-value pairs and have the following structure:

  • The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents.

3

{

field1: value1,

field2: value2,

field3: value3,

...

fieldN: valueN

}

4 of 43

Document with different types of values

  • i)Document with Scalar Values
    • A variable that holds one value at a time. It is a single component that assumes a range of number or string values

  • ii)Document with Documents as values
    • embedded document: related data attached in a single structure or document

  • iii)Document with Array as values
    • A value made up of multiple elements is referred to as an array

4

5 of 43

Document with different types of values

5

6 of 43

CRUD��Create, Read, Update, Delete

7 of 43

Create Operations

  • Create or insert operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.

  • Example

7

8 of 43

Create or Insert operations

  • Insert data to a new collection, or to a collection that has been created before.
  • There are three methods of inserting data.
    1. insertOne() is used to insert a single document only.
    2. insertMany() is used to insert more than one document.
    3. insert() is used to insert documents as many as you want.

8

9 of 43

Inserting Data

  • insertOne()

  • insertMany()

  • insert() method : inserted a new property called location on the document

9

db.myCollection.insertOne(

{

"name": "navindu", "age": 22

}

)

db.myCollection.insertMany([

{ "name": "navindu", "age": 22 },

{ "name": "kavindu", "age": 20 },

{ "name": "john doe", "age": 25}

])

>db. myCollection.insert({"location": "colombo" }),

WriteResult({ "nInserted" : 1 })

10 of 43

Insert a Single Document

  • insertOne() returns a document that includes the newly inserted document's _id field value. For an example of a return document

10

db.inventory.find( { item: "canvas" } )

11 of 43

Insert Multiple Documents

  • insertMany() returns a document that includes the newly inserted documents _id field values. See the reference for an example.

11

db.inventory.insertMany([

{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },

{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },

{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }

])

12 of 43

Insert Behavior

  • Collection Creation
    • If the collection does not currently exist, insert operations will create the collection.
  • _id Field
    • In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.
    • This also applies to documents inserted through update operations with upsert: true.
  • Atomicity
    • All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity,
  • Write Acknowledgement
    • With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations

12

13 of 43

Read / Query Operations

  • Read operations retrieve documents from a collection; i.e. query a collection for documents. MongoDB provides the following methods to read documents from a collection:

    • The find() Method
    • The pretty() Method
    • The findOne() method
    • RDBMS Where Clause Equivalents in MongoDB
    • AND in MongoDB
    • OR in MongoDB
    • Using AND and OR Together
    • NOR in MongoDB
    • NOT in MongoDB

13

14 of 43

The find() Method

  • To query data from MongoDB collection, you need to use MongoDB's find() method.
  • Syntax

  • find() method will display all the documents in a non-structured way.
  • Example

14

>db.COLLECTION_NAME.find()

> db.mycol.find()

{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", }

{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z“)} ]

}

15 of 43

The pretty() Method

  • To display the results in a formatted way, you can use pretty() method.
  • Syntax

  • find() method will display all the documents in a non-structured way.
  • Example

15

>db.COLLECTION_NAME.find().pretty()

> db.mycol.find().pretty()

{

"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),

"title" : "MongoDB Overview",

}

{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"),

"title" : "NoSQL Database",

"comments" :

[

{ "user" : "user1",

"message" : "My first comment",

"dateCreated" : ISODate("2013-12-09T21:05:00Z“)

}

]

}

16 of 43

The findOne() method

  • Apart from the find() method, there is findOne() method, that returns only one document.
  • Syntax

  • find() method will display all the documents in a non-structured way.
  • Example

16

>db.COLLECTIONNAME.findOne()

> db.mycol.findOne({title: " NoSQL Database "})

{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"),

"title" : "NoSQL Database",

"comments" :

[

{ "user" : "user1",

"message" : "My first comment",

"dateCreated" : ISODate("2013-12-09T21:05:00Z“)

}

]

}

17 of 43

RDBMS Where Clause Equivalents in MongoDB

17

Operation

Syntax

Example

RDBMS Equivalent

Equality

{<key>:{$eg;<value>}}

db.mycol.find({"by":"tutorials point"}).pretty()

where by = 'tutorials point'

Less Than

{<key>:{$lt:<value>}}

db.mycol.find({"likes":{$lt:50}}).pretty()

where likes < 50

Less Than Equals

{<key>:{$lte:<value>}}

db.mycol.find({"likes":{$lte:50}}).pretty()

where likes <= 50

Greater Than

{<key>:{$gt:<value>}}

db.mycol.find({"likes":{$gt:50}}).pretty()

where likes > 50

Greater Than Equals

{<key>:{$gte:<value>}}

db.mycol.find({"likes":{$gte:50}}).pretty()

where likes >= 50

Not Equals

{<key>:{$ne:<value>}}

db.mycol.find({"likes":{$ne:50}}).pretty()

where likes != 50

Values in an array

{<key>:{$in:[<value1>, <value2>,……<valueN>]}}

db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty()

Where name matches any of the value in :["Raj", "Ram", "Raghu"]

Values not in an array

{<key>:{$nin:<value>}}

db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty()

Where name values is not in the array :["Ramu", "Raghav"] or, doesn’t exist at all

18 of 43

AND, OR, NOR, NOT Operation

  • To query documents based on the certain condition
  • Syntax

  • AND and OR together

18

>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })

>db.mycol.find({ $or: [ {<key1>:<value1>}, { <key2>:<value2>} ] })

>db.mycol.find({ $not: [ {<key1>:<value1>}, { <key2>:<value2>} ] })

>db.mycol.find({ $nor: [ {<key1>:<value1>}, { <key2>:<value2>} ] })

>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"}, {"title": "MongoDB Overview"}]}).pretty()

 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'

19 of 43

Perform Query Operation for the following situations

  • i)Query on nested documents
  • ii)Query an array
  • ii)Query an array of nested documents
  • iv)Geospatial Queries

19

db.inventory.insertMany( [

{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },

{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

]);

20 of 43

Perform Query Operation for the following situations

  • i)Query on nested documents

20

db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

db.inventory.find( { "size.uom": "in" } )

db.inventory.insertMany( [

{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },

{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

]);

21 of 43

Perform Query Operation for the following situations

  • ii)Query an array

21

db.inventory.insertMany([

{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },

{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },

{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },

{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },

{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }

]);

Query an Array for an Element

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

db.inventory.find( { dim_cm: { $gt: 25 } } )

Query an Array with Compound Filter Conditions on the Array Elements

db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

Query for an Array Element that Meets Multiple Criteria

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

22 of 43

Perform Query Operation for the following situations

  • iii)Query an array of nested documents

22

db.inventory.insertMany( [

{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },

{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },

{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },

{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },

{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }

]);

Query for a Document Nested in an Array

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )

Specify a Query Condition on a Field in an Array of Documents

db.inventory.find( { 'instock.qty': { $lte: 20 } } )

Use the Array Index to Query for a Field in the Embedded Document

db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )

A Single Nested Document Meets Multiple Query Conditions on Nested Fields

db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

23 of 43

Perform Query Operation for the following situations

  • iv)Geospatial Queries

23

<field>: { type: <GeoJSON type> , coordinates: <coordinates> }

location: {

type: "Point",

coordinates: [-73.856077, 40.848447]

}

Legacy Coordinate Pairs

Specify via an array

<field>: [ <x>, <y> ]

<field>: [<longitude>, <latitude> ]

Specify via an embedded document:

<field>: { <field1>: <x>, <field2>: <y> }

<field>: { <field1>: <longitude>, <field2>: <latitude> }

24 of 43

Update Operations

  • Update operations modify existing documents in a collection. MongoDB provides the following methods to update documents of a collection:
    1. updateOne()
    2. updateMany()
    3. replaceOne()
    4. findAndModify()
  • In MongoDB, update operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
  • You can specify criteria, or filters, that identify the documents to update. These filters use the same syntax as read operations.

24

>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

25 of 43

updateOne() method

  • This methods updates a single document which matches the given filter.
  • Syntax

  • Example

25

>db.COLLECTION_NAME.updateOne(<filter>, <update>)

> db.empDetails.updateOne(

{First_Name: 'Radhika'},

{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}

)

{

"acknowledged" : true,

"matchedCount" : 1,

"modifiedCount" : 0 } >

26 of 43

updateMany() method

  • The updateMany() method updates all the documents that matches the given filter.
  • Syntax

  • Example

26

>db.COLLECTION_NAME.updateMany(<filter>, <update>)

> db.empDetails.updateMany(

{Age:{ $gt: "25" }},

{ $set: { Age: '00'}}

)

{

"acknowledged" : true,

"matchedCount" : 2,

"modifiedCount" : 2

}

27 of 43

replaceOne() method

  • Replaces a single document i.e., first matching document within the collection that matches the filter
  • Syntax

  • Example

27

> db.collection.replaceOne(filter, replacement, options)

db.collection.replaceOne(

<filter>,

<replacement>,

{

upsert: <boolean>,

writeConcern: <document>,

collation: <document>,

hint: <document|string>

}

)

28 of 43

findAndModify() method

  • Modifies and returns a single document. By default, the returned document does not include the modifications made on the update.
  • Syntax:

  • Example

28

> db.collection.findAndModify(document)

db.people.findAndModify(

{

query: { name: "Andy" },

update: { $inc: { score: 1 } },

upsert: true

}

)

29 of 43

Delete Operations

  • Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection:
    1. deleteMany()
    2. deleteOne()
    3. findOneAndDelete()

29

30 of 43

deleteOne() method

  • Allows you to delete a single document from a collection..

  • Syntax

30

> db.collection.deleteOne(filter, option)

db.products.insertMany([

{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},

{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},

{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},

{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},

{ "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}

])

Using the deleteOne() method to delete a single document

db.products.deleteOne({_id: 1}) { "acknowledged" : true, "deletedCount" : 1 }

Using the deleteOne() method to delete the first document from a collection

db.products.deleteOne({}) { "acknowledged" : true, "deletedCount" : 1 }

31 of 43

deleteMany() method

  • Allows you to remove all documents that match a condition from a collection.

  • Syntax

31

> db.collection.deleteMany(filter, option)

db.products.insertMany([

{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},

{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},

{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},

{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},

{ "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}

])

Using the deleteMany() method to delete multiple documents

db.products.deleteMany({ price: 899 }) { "acknowledged" : true, "deletedCount" : 2 }

Using the deleteMany() method to delete all documents

db.products.deleteMany({})

32 of 43

findOneAndDelete() method

  • Allows you to deletes a single document, and returns the deleted document.

  • Syntax

32

> db.collection.findOneAndDelete(filter, option)

db.pets.insertMany([

{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }

{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }

{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }

{ "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 }

{ "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 }

{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } }

{ "_id" : 7, "name" : "Jake", "type" : "Dog", "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] }

db.pets.findOneAndDelete( { "type": "Cat" } )

Result

{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }

db.pets.find()

{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 } { "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } } { "_id" : 7, "name" : "Jake", "type" : "Dog", "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] }

33 of 43

Projection

  • In MongoDB, projection simply means selecting fields to return from a query.
  • By default, the find() and findOne() methods return all fields in matching documents. Most of the time you don’t need data from all the fields.
  • To select fields to return from a query, you can specify them in a document and pass the document to the find() and findOne() methods. This document is called a projection document.

33

>db.COLLECTION_NAME.find({},{KEY:1})

> db.products.find({price: 899});

db.products.insertMany([

{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},

{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},

{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},

{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},

{ "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}

])

34 of 43

Projection

  • 1) Returning all fields in matching documents

  • 2) Returning specified fields including the _id field

34

> db.products.find({price: 899});

{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},

{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},

> db.products.find({}, {

name: 1,

price: 1

});

{ "_id" : 1, "name" : "xPhone", "price" : 799 }

{ "_id" : 2, "name" : "xTablet", "price" : 899 }

{ "_id" : 3, "name" : "SmartTablet", "price" : 899 }

{ "_id" : 4, "name" : "SmartPad", "price" : 699 }

{ "_id" : 5, "name" : "SmartPhone", "price" : 599 }

> db.products.find({}, {

name: 1,

price: 1

,

_id: 0

});

{ "name" : "xPhone", "price" : 799 }

{ "name" : "xTablet", "price" : 899 }

{ "name" : "SmartTablet", "price" : 899 }

{ "name" : "SmartPad", "price" : 699 }

{ "name" : "SmartPhone", "price" : 599 }

35 of 43

Projection

  • 3) Returning all fields except for some fields

35

> db.products.find({_id:1}, {

releaseDate: 0,

spec: 0,

storage: 0

}).pretty()

{

"_id" : 1,

"name" : "xPhone",

"price" : 799,

"color" : [

"white",

"black"

],

"inventory" : [

{

"qty" : 1200,

"warehouse" : "San Jose"

}

]

}

36 of 43

Projection

  • 4) Returning fields in embedded documents

36

> db.products.find({_id:1}, {

name: 1,

price: 1,

"spec.screen": 1

}).pretty()

{

"_id" : 1,

"name" : "xPhone",

"price" : 799,

"spec" : {

"screen" : 6.5

}

}

MongoDB 4.4

> db.products.find({_id:1}, {

name: 1,

price: 1,

spec : { screen: 1

}

}).pretty()

37 of 43

Projection

  • 5) Projecting fields on embedded documents in an array
    • The following example specifies a projection that returns:
      1. the _id field (by default)
      2. The name field
      3. And qty field in the documents embedded in the inventory array.

37

> db.products.find({}, {

name: 1,

"inventory.qty": 1

});

{ "_id" : 1, "name" : "xPhone", "inventory" : [ { "qty" : 1200 } ] }

{ "_id" : 2, "name" : "xTablet", "inventory" : [ { "qty" : 300 } ] }

{ "_id" : 3, "name" : "SmartTablet", "inventory" : [ { "qty" : 400 }, { "qty" : 200 } ] }

{ "_id" : 4, "name" : "SmartPad", "inventory" : [ { "qty" : 1200 } ] }

{ "_id" : 5, "name" : "SmartPhone" }

38 of 43

Limiting Records

  • The method accepts one number type argument, which is the number of documents that you want to be displayed.
  • Syntax

  • Example

  • If you don't specify the number argument in limit() method then it will display all documents from the collection.

38

>db.COLLECTION_NAME.find().limit(NUMBER)

{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},

{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},

{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}

>db.mycol.find({},{"title":1,_id:0}).limit(2)

Display only two documents while querying the document.

{"title":"MongoDB Overview"}

{"title":"NoSQL Overview"}

>

39 of 43

Sorting Records

  • The method accepts a document containing a list of fields along with their sorting order.
  • To specify sorting order 1 and -1 are used.
    • 1 is used for ascending order while
    • -1 is used for descending order.
  • Syntax
  • Example

39

>db.COLLECTION_NAME.find().sort({KEY:1})

{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},

{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},

{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})

{"title":"Tutorials Point Overview"}

{"title":"NoSQL Overview"}

{"title":"MongoDB Overview"}

>

40 of 43

Indexes in Mongodb

  • Indexes are special data structures, that store a small portion of the data set in an easy-to-traverse form.
  • The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index.
  • 1. The createIndex() Method

40

>db.COLLECTION_NAME.createIndex({KEY:1})

>db.mycol.createIndex({"title":1})

{ "createdCollectionAutomatically" : false,

"numIndexesBefore" : 1,

"numIndexesAfter" : 2,

"ok" : 1

}

>

41 of 43

Indexes in Mongodb

  • 2. The dropIndex() method
    • Key is the name of the file on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.

41

>db.COLLECTION_NAME.dropIndex({KEY:1})

> db.mycol.dropIndex({"title":1})

{

“ok" : 0,

"errmsg" : "can't find index with key: { title: 1.0 }",

"code" : 27, "codeName" :

"IndexNotFound"

}

42 of 43

Indexes in Mongodb

  • 2. The dropIndex() method
    • Key is the name of the file on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.

  • Example

42

>db.COLLECTION_NAME.dropIndexes()

> db.mycol.createIndex({"title":1,"description":-1})

>db.mycol.dropIndexes({"title":1,"description":-1})

{ "nIndexesWas" : 2,

"ok" : 1 } >

43 of 43

43