0% found this document useful (0 votes)
2 views11 pages

Query

The document provides instructions on how to manage databases and collections in MongoDB, including creating, inserting, updating, and deleting documents. It outlines methods such as show dbs, use, createCollection(), insertOne(), insertMany(), find(), and updateOne(), among others. Additionally, it explains querying data with operators and methods like limit() and skip().

Uploaded by

niranjana1805.k
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

Query

The document provides instructions on how to manage databases and collections in MongoDB, including creating, inserting, updating, and deleting documents. It outlines methods such as show dbs, use, createCollection(), insertOne(), insertMany(), find(), and updateOne(), among others. Additionally, it explains querying data with operators and methods like limit() and skip().

Uploaded by

niranjana1805.k
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Show all databases

To see all available databases, in your terminal type show dbs.

Change or Create a Database


You can change or create a new database by typing use then the name of
the database.

Example
Create a new database called "blog":

use blog

Method 1
You can create a collection using the createCollection() database method.

Example
[Link]("posts")

Method 2
You can also create a collection during the insert process.

Example
We are here assuming object is a valid JavaScript object containing post
data:

[Link](object)

Insert Documents
There are 2 methods to insert documents into a MongoDB database.

insertOne()
To insert a single document, use the insertOne() method.

This method inserts a single object into the database.


[Link]({

title: "Post Title 1",

body: "Body of post.",

category: "News",

likes: 1,

tags: ["news", "events"],

date: Date()

})

insertMany()
To insert multiple documents at once, use the insertMany() method.

This method inserts an array of objects into the database.


[Link]([
{
title: "Post Title 2",
body: "Body of post.",
category: "Event",
likes: 2,
tags: ["news", "events"],
date: Date()
},
{
title: "Post Title 3",
body: "Body of post.",
category: "Technology",
likes: 3,
tags: ["news", "events"],
date: Date()
},
{
title: "Post Title 4",
body: "Body of post.",
category: "Event",
likes: 4,
tags: ["news", "events"],
date: Date()
}
])

Find Data
There are 2 methods to find and select data from a MongoDB
collection, find() and findOne().

find()
To select data from a collection in MongoDB, we can use
the find() method.

This method accepts a query object. If left empty, all documents will be
returned.

Example
[Link]()

findOne()
To select only one document, we can use the findOne() method.
This method accepts a query object. If left empty, it will return the first
document it finds.

Note: This method only returns the first match it finds.

Example
[Link]()

Querying Data
To query, or filter, data we can include a query in
our find() or findOne() methods.

Example
[Link]( {category: "News"} )

Projection
Both find methods accept a second parameter called projection.

This parameter is an object that describes which fields to include in the


results.

Note: This parameter is optional. If omitted, all fields will be included in


the results.

Example
This example will only display the title and date fields in the results.

[Link]({}, {title: 1, date: 1})

We use a 1 to include a field and 0 to exclude a field.

Example
This time, let's exclude the _id field.

[Link]({}, {_id: 0, title: 1, date: 1})

Let's exclude the date category field. All other fields will be included in the
results.

Example
[Link]({}, {category: 0})

We will get an error if we try to specify both 0 and 1 in the same object.

Example
[Link]({}, {title: 1, date: 0})

Update Document
To update an existing document we can use
the updateOne() or updateMany() methods.

The first parameter is a query object to define which document or


documents should be updated.

The second parameter is an object defining the updated data.

updateOne()
The updateOne() method will update the first document that is found
matching the provided query.

Let's see what the "like" count for the post with the title of "Post Title 1":

Example
[Link]( { title: "Post Title 1" } )

Insert if not found


If you would like to insert the document if it is not found, you can use
the upsert option.

Example
Update the document, but if not found insert it:

[Link](
{ title: "Post Title 5" },

$set:

title: "Post Title 5",

body: "Body of post.",

category: "Event",

likes: 5,

tags: ["news", "events"],

date: Date()

},

{ upsert: true }

updateMany()
The updateMany() method will update all documents that match the
provided query.

Example
Update likes on all documents by 1. For this we will use
the $inc (increment) operator:

[Link]({}, { $inc: { likes: 1 } })

Now check the likes in all of the documents and you will see that they have all
been incremented by 1.

Delete Documents
We can delete documents by using the
methods deleteOne() or deleteMany().

These methods accept a query object. The matching documents will be


deleted.
deleteOne()
The deleteOne() method will delete the first document that matches the
query provided.

Example
[Link]({ title: "Post Title 5" })

deleteMany()
The deleteMany() method will delete all documents that match the query
provided.

Example
[Link]({ category: "Technology" })

here are many query operators that can be used to compare and
reference document fields.

Comparison
The following operators can be used in queries to compare values:

 $eq: Values are equal


 $ne: Values are not equal
 $gt: Value is greater than another value
 $gte: Value is greater than or equal to another value
 $lt: Value is less than another value
 $lte: Value is less than or equal to another value
 $in: Value is matched within an array

Logical
The following operators can logically compare multiple queries.

 $and: Returns documents where both queries match


 $or: Returns documents where either query matches
 $nor: Returns documents where both queries fail to match
 $not: Returns documents where the query does not match
Evaluation
The following operators assist in evaluating documents.

 $regex: Allows the use of regular expressions when evaluating field


values
 $text: Performs a text search
 $where: Uses a JavaScript expression to match documents

[Link]({$and:[{"sex":"Male"},{"grd_point":{ $gte: 31 }},


{"class":"VI"}]}).pretty();

[Link]( {"age": { $not: {$lt : 12}}}).pretty();

OR Command

[Link]({

$or: [

{ branch: "ECE" },

{ joining_year: 2017 }

})

limit() method
The .limit() method specifies the maximum number of documents to return in the
result set.

 Syntax: [Link]().limit(<number>)

 Example: To return only the first 5 documents from a products collection:

javascript
[Link]().limit(5)

 You must apply .limit() to the cursor before retrieving documents for optimal
performance.

skip() method
The .skip() method omits a specified number of documents from the beginning of
the result set and returns the rest.

 Syntax: [Link]().skip(<number>)

 Example: To skip the first 10 documents and return the rest:


javascript
[Link]().skip(10)

In Operator

[Link]({

title: "Post Title 1",

body: "Body of post.",

category: "News",

likes: 1,

tags: ["news", "events"],

date: Date()

})

[Link]({

title: "Post Title 1",

body: "Body of post.",

category: "News",

likes: 1,

tags: ["video", "events"],

date: Date()

})

[Link]({ tags: { $in: ["video", "cool"] } });

How $elemMatch works


Consider a collection of books, where each document has a reviews array of
embedded documents:

json
{
"title": "The Great Gatsby",
"reviews": [
{ "rating": 5, "reviewer": "John" },
{ "rating": 3, "reviewer": "Jane" }
]
}

The $elemMatch Solution

The $elemMatch operator ensures that all conditions are met by a single element
within the array:

javascript
[Link]({
reviews: {
$elemMatch: { rating: 5, reviewer: "Jane" }
}
});

[Link](

"title": "The Great Gatsby",

"reviews": [

{ "rating": 5, "reviewer": "John" },

{ "rating": 3, "reviewer": "Jane" }

})

[Link](

"title": "The Great Gatsby",

"reviews": [

{ "rating": 7, "reviewer": "John" },

{ "rating": 3, "reviewer": "Jane" }

})

[Link]({

reviews: {

$elemMatch: { rating: 5,reviewer:"John" }


}

});

Output
{ "_id" : ObjectId("693fad7c5dad943b138952ff"), "title" : "The Great
Gatsby", "reviews" : [ { "rating" : 5, "reviewer" : "John" }, { "rating" :
3, "reviewer" : "Jane" } ] }

You might also like