0% found this document useful (0 votes)
5 views

Notes 2

Uploaded by

ashirvad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Notes 2

Uploaded by

ashirvad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Editing "MongoDB" 27/05/23, 7:26 PM

Add Cover Add Subtitle

MongoDB

How to add multiple records together?


To add multiple records at once in MongoDB we can use:

JavaScript

db.collectionName.insertMany([
{
key1: value1,
key2: value2
},
{
key1: value1,
key2: value2,
key3: value3,
.
.
.
},
{
key5: value5,

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 1 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

key7: value7,
.
.
}
]);

Can we add an array in the JSON in MongoDB?


We can simply use [] to add an array.

How to import sample DB in MongoDB?


To get some free sample datasets you can check out this Github link:
https://github.com/neelabalan/mongodb-sample-dataset.

You can pick any folder and download the dataset which is present in JSON
format.

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 2 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

&github.com

•Editing"MongoDB" Gmongodbsampledataset-GoogleSearch (mongodb-sample-dataset/data.jsonatmain•neelabalan/mongod-sample-

ProductSolutionsOpenSourcePricing Search Signin Signup

#neelabalan/mongodb-sample-datasetPublic •Notifications Fork127 Star164

<>Code ©Issues ??Pullrequests ©ActionshEProjects ©Security I~Insights

mainmongodb-sample-dataset/sample_weatherdata/data.json Gotofile

neelabalaninitialcommit Latestcommit1462716onJan23,2021CHistory

831contributor

18MB Download

Viewraw
(Sorryaboutthat,butwecan'tshowfilesthatarethisbigrightnow.)

•2023GitHub,Inc. Terms Privacy Security Status Docs ContactGitHub Pricing API Training Blog About

After the file is downloaded you can import this data using MongoDB
Compass.

Create a new Database (we can directly create it using MongoDB


Compass)

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 3 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

We can give a name to the database and give the first collection name
also directly using MongoDB Compass.

MyQueries Databases Performance


localhost:27017

{}MyQueries

•Databases

Search

•STUDENTS_Database

•University

•&admin CreateDatabase
•&chatapp
DatabaseName
•config
Weather
•gd_backend

•goodreads CollectionName
•local
weather_data
•&mba_db

"&new_db •Time-Series
Time-seriescollectionsefficientlystoresequencesofmeasurementsoveraperiod
•noti_db oftime.LearnMore&
§project
›Additionalpreferences(e.g.Customcollation,Capped,Clusteredcollections)
•twitter_Dev

Cancel CreateDatabase

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 4 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

Once you click on create a database, a brand new empty db will be


>_MONGOSH

created.

Now click on Add Data, which will give you two options:

Either you can import from JSON or CSV

Or you can manually insert the document.

We will go for Option 1.

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 5 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

•Documents
localhost:27017 Weather.weather...

{}MyQueries

•Databases
Weather.weather_data DOCUMENTS

Search Documents Aggregations Schema ExplainPlan Indexes Validation

•STUDENTS_Database
Filter&Ov Typeaquery:{field:'value'} Reset Find <> More
•University

&Weather 0-0of0S
©ADDDATA [CEXPORTCOLLECTION
Iweather_data
ImportJSONorCSVfile
•admin

Schatapp Insertdocument

•config

•gd_backend

•§goodreads
"§local Thiscollectionhasnodata

§mba_db ItonlytakesafewsecondstoimportdatafromaJSONorCSV
file.
&new_db

§noti_db ImportData

•project

••twitter_Dev

>MONGOSH

It will open the file explorer where you can select the JSON we just
downloaded.

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 6 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

Click on import and it will automatically import the data from the JSON

After it finishes importing, it should look like this:

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 7 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

•Documents
localhost:27017 Weather.weather...

{}MyQueries
Weather.weather_data 10.0k
•Databases DOCUMENTS

Search Documents Aggregations Schema ExplainPlan Indexes Validation

•STUDENTS_Database
Filter&O Typeaquery:{field:'value'} Reset Find <> More
•University

&Weather §EXPORTCOLLECTION 1-20of10000


•ADDDATA

Iweather_data
•admin id:ObjectId('5553a9984b02cf7151190b8')
st:"×+47600-047900"
•chatapp ts:1984-03-0513:00:00.000+00:00
•position:Object
•config elevation:9999
callLetters:"VCSZ"
•gd_backend qualityControlProcess:"V020"
dataSource:"4"
•§goodreads type:"FM-13"
"§local •airTemperature:Object
•dewPoint:Object
§mba_db pressure:Object
wind:Object
&new_db visibility:Object
skyCondition:Object
§noti_db sections:Array
•precipitationEstimatedobservation:Object
•project

•twitter_Dev
_id:ObjectId('5553a9984b02cf7151190b9')
st:"×+45200-066500"
ts:1984-03-0514:00:00.000+00:00
•position:Object
elevation:9999
callLetters:"VC81"
qualityControlProcess:"V020'

Importcompleted.
10000documentswritten. Ire:Object
bject
•pressure:Oblect
wind•Obtect

›_MONGOSH

How to import without MongoDB Compass?


We can use a terminal or CMD to import data without a compass.

Open your terminal or CMD.

Change the directory to the one where you have downloaded the
JSON. If you are using Windows refer to this link to understand how
to change the directory from cmd.

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 8 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

Now we can use a MongoDB tool called as mongoimport (generally by


default installed with MongoDB). We can use the following command:

JavaScript

mongoimport --db db_name --collection collection_name --


file data.json;

~/Downloads 2850 18:12


$mongoimport--dbnew_weather_b--collectionweather_data--filedata.json;
2023-05-27718:15:43.724+0530 connectedto:mongodb://localhost/
2023-05-2718:15:44.740+0530 10000document(s)importedsuccessfully.0document(s)failedtoimport.

~/Downloads 2851 18:15

You can check the import directly from mongosh or compass

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 9 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

ThemonitoringdatawillbeavailableonaMongoDBwebsitewithauniqueURLaccessibletoyou
andanyoneyousharetheURLwith.MongoDBmayusethisinformationtomakeproduct
improvementsandtosuggestMongoDBproductsanddeploymentoptionstoyou.

Toenablefreemonitoring,runthefollowingcommand:b.enableFreeMonitoring()
Topermanentlydisablethisreminder,runthefollowingcommand:b.disableFreeMonitoring()

Warning:Found~/.mongorc.js,butnot~/.mongoshrc.js.~/.mongorc.jswillnotbeloaded.
Youmaywanttocopyorrename~/.mongorc.jsto~/.mongoshrc.js.
test>showdbs;
STUDENTS_Database 88.00KiB
University 72.00KiB
Weather 2.49MiB
admin 40.00KiB
chatapp 72.00KiB
config 108.00KiB
gd_backend 416.00KiB
goodreads 416.00KiB
local 104.00KiB
mba_db 504.00KiB
newdb 85.89MiB
new_weather_db 2.57MiB
noti_db 72.00KiB
project 76.00KiB
testing 2.55MiB
twitter_Dev 360.00KiB
test>usenew_weather_db
switchedtodbnew_weather_db
new_weather_db>showcollections
weather_data
new_weather_db>

Let's explore the DB we imported

How to see the count of documents in a collection?


There is a count function that we can use

JavaScript

db.collectionName.find().count();

new_weather_db>db.weather_data.find().count()
(node:88641)[MONGODBDRIVER]Warning:cursor.countisdeprecatedandwillberemovedinthenextmajorversion,
usecollection.estimatedDocumentCountorcollection.countDocumentsinstead
(Use 'node_-trace-warninas.. toshowwherethewarningwascreated)
10000
new_weatherdb>

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 10 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

How to handle the printing of huge amounts of data?


If you have a huge amount of data, just like we have here approx 10,000
documents, if you try to execute db.collectionName.find in your mongosh
then will not print all the 10,000 records, becuase it cannot handle that in the
shell. If you try it then in the console, it will print some data and then gives
you a prompt of Try "it" for more

mongoshmongodb:|/127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000(I?directConnection=true\&se)961 ~/Downloads(-zsh)

speed:{rate:9.8,quality:'1'}
},
visibility:{
distance:€value:50000,quality:'1'3,
variability:{value:'N',quality:'9'}
},
skyCondition:{
ceilingHeight:{value:22000,quality:'1',determination:'C'},
cavok:'N'
},
sections:['AGI', 'AYI','GFI','MW'1,
precipitationEstimatedObservation:{discrepancy:'0',estimatedWaterDepth:999},
pastWeatherObservationManual:[

atmosphericCondition:value:'O',quality:'1'3,
period:{value:6,quality:'1'}
}
1,
skyConditionObservation:{
totalCoverage:{value:'00',opaque:'99',quality:'1'},
lowestCloudCoverage:{value:'00',quality:'1'3,
lowcloudGenus:{value:'00',quality:'1'3,
lowestCloudBaseHeight:{value:99999,quality:'9'},
midCloudGenus:€value:'00',quality:
highcloudGenus:value:'00%,Quality:'1'
},
presentweatherObservationManual:|{condition:'02',quality:'1'}1

Type"it"formore
new_weather_db>
If you write it and press enter then you will get next group of data.

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 11 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

mongoshmongodb:|/127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000(I?directConnection=true|&se)961 ~/Downloads(-zsh)

precipitationEstimatedObservation:{discrepancy:'2',estimatedWaterDepth:0},
pastWeather0bservationManual:
{
atmosphericCondition:{value:'o',quality:'1'},
period:<value:6,quality:'1'}
}
1,
skyConditionObservation:{
totalCoverage:{value:'08',opaque:'99',quality:'1'3,
lowestCloudCoverage:€value:'08',quality:'1'3,
lowcloudGenus:{value:'06',quality:'1'3,
lowestCloudBaseHeight:€value:450,quality:'1'7,
midCloudGenus:{value:'99',quality:'9'3,
highcloudGenus:{value:'99',quality:'9'}
3.
atmosphericPressureChange:{
tendency:{code:'7',quality:'1'3,
quantity3Hours:value:0.6,quality:'1'3,
quantity24Hours:{value:99.9,quality:'9'}
},
presentWeatherobservationManual:I{condition:'02',quality:'1'31,
seasurfaceTemperature:{value:15.5,quality:'9'},
waveMeasurement:{
method:'M',
waves:{period:3,height:1,quality:'9'},
seaState:{code:'99',quality:'9'}
}

Type"it"formore
new_weather_db>it

How to get a certain number of documents?


We can use a function called as limit

JavaScript

db.collectionName.find().limit(no_of_records_to_fetch);

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 12 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

mongoshmongodb:|/127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000(I?directConnection=true\&se)961 ~/Downloads(-zsh)

new_weather_db>db.weather_data.find().limit(3)
{

_id:ObjectId("5553a998e4b02cf7151190b9"),
st:'x+45200-066500',
ts:ISODate("1984-03-05T14:00:00.000Z"),
position:{type:'Point',coordinates:1-66.5,45.21},
elevation:9999,
callLetters:'VC81',
qualityControlProcess:'V020',
dataSource:'4'
type:'FM-13'
airTemperature:{value:-4.7,quality:'1'},
dewPoint:{value:999.9,quality:'9'3,
pressure:€value:1025.9,quality:'1'},
wind:{

direction:Iangle:999,quality:'9'3,
type:'9',
speed:<rate:999.9,quality:'9'}
},
visibility:{
distance:{value:999999,quality:'9'3,
variability:{value:'N',quality:'9'}
3,
skyCondition:{
ceilingHeight:{value:99999,quality:'9',determination:'9'3,
cavok:'N'
},
sections:['AGI'1,
precipitationEstimatedObservation:discrepancy:'2',estimatedWaterDepth:999}
3,

How to set an offset while querying data?


We can set an offset using the skip function. Using the skip function we can
skip some records and then start fetching records post the skip.

JavaScript

db.collectionName.find().skip(5).limit(3)

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 13 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

mongoshmongodb:|/127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000(I?directConnection=true\&se)961 ~/Downloads(-zsh)

new_weather_db>db.weather_data.find().skip(10).limit(2);
{

_id:ObjectId("5553a998e4b02cf7151190b8"),
st:'x+47600-047900',
ts:ISODate("1984-03-05T13:00:00.000Z"),
position:{type:'Point',coordinates:1-47.9,47.61},
elevation:9999,
callLetters:'VCSZ',
qualityControlProcess:'V020',
dataSource:'4'
type:'FM-13'
airTemperature:{value:-3.1,quality:'1'},
dewPoint:{value:999.9,quality:'9'},
pressure:€value:1015.3,quality:'1'},
wind:{

direction:Iangle:999,quality:'9'3,
type:'9',
speed:<rate:999.9,quality:'9'}
},
visibility:{
distance:{value:999999,quality:'9'3,
variability:{value:'N',quality:'9}
3,
skyCondition:{
ceilingHeight:{value:99999,quality:'9',determination:'9'3,
cavok:'N'
},
sections:['AGI'1,
precipitationEstimatedObservation:discrepancy:'2',estimatedWaterDepth:999}
3,
Saved Upgrade Preview Publish
How do filter records based on a condition?
To filter the records, we can pass an object in the arguments of the find
function, where we can add out conditions.

JavaScript

db.collectionName.find({key1: value1, key2: value2})

Projections
https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 14 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

If we want to not get all the properties of the JSON, and instead get some
specific key-value pairs, this process is called Projection. In the world of
SQL, if you do SELECT * FROM TABLE; then you get all the columns but if you
do SELECT name, address FROM TABLE; you only get name and address. This
same thing is achieved in Projections.

How to do projections?

So the first argument of the find function is an object which takes filtration
criteria. It can accept another argument as an object, where we can write
whatever properties we have to include and assign them a value true.

JavaScript

db.collectionName.find({filter1: value1...}, {property1: true,


property2: true....});

You can also pass the first argument as an empty JSON object.

newweather_db>db.weather.data.find(<},{position:true,visibility:true}

If we want to manually exclude specific properties, you can write their names
with false value allocated:

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 15 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

Now this will bring everything apart from pastWeatherObservationManual and


skyConditionObservation

How to delete a document?


If we want to delete some documents we can use functions like deleteOne ,
deleteMany and findByIdAndDelete .

JavaScript

db.collectionName.deleteOne({filter1: value1, filter2:


value2..});

new_weather_db>db.weather_data.deleteOne({st:'x-19300+060300'})
{acknowledged:true,deletedCount:1}
new_weather_db>db.weather_data.find().count()
9999

new_weather_db>

JavaScript

db.collectionName.deleteMany({filter1: value1, filter2:


value2..});

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 16 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

new_weather_db>db.weather_data.find({callLetters:'FNPG'}).count
7

new_weather_db>b.weather_data.deleteMany({callLetters:'FNPG'3)
{acknowledged:true,deletedCount:7}
new-_weather_db>db.weather_data.find().count()
9992
newweatherdb>

new_weather_b>db.weather_data.deleteOne({_id:ObjectId("5553a998e4b02cf7151190b9"
{acknowledged:true,deletedCount:1}
new_weather_db>db.weather_data.find(f_id:ObjectId("5553a998e4b02cf7151190b9")3)
newweatherdb>

We can similarly use findOneAndDelete to filter the data and then delete one
record it. Docs

How to update a record?


To Update records we can use updateOne , updateMany and a few similar
functions. These functions take two arguments,

!" Filtration criteria viz. how to filter what data to update

$" With what value we should update

JavaScript

db.collectionName.updateOne({filter1: value1}, {$operator:


{key1: value1, key2: value2...}})

Now MongoDB provides us some operators for these updates for example:

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 17 of 18
Editing "MongoDB" 27/05/23, 7:26 PM

$set -> This will allocate the value to the key directly passed in the
object

$inc -> This will increment the value in the key

new_weather_db>db.weather_data.updateOne(<_id:ObjectId("5553a9984b02cf7151190c0")),<$inc:felevation:
{
acknowledged:true,
insertedId:null,
matchedCount:1,
modifiedCount:1,
upsertedCount:0

To decrease we can do $inc with a negative value.

new-_weather_b>db.weather_data.updateOne(<_id:ObjectId("5553a998e4b02cf7151190c0")},<$inc:{elevation:-133);
{
acknowledged:true,
insertedId:null,
matchedCount:1,
modifiedCount:1,
upsertedCount:0

If you will use updateMany then all the records which are complying to the
filteration criteria will be update.

https://hashnode.com/draft/6471f3c0de2159000f618c28 Page 18 of 18

You might also like