Notes 2
Notes 2
MongoDB
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,
.
.
}
]);
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
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.
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
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
created.
Now click on Add Data, which will give you two options:
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
•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
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
•STUDENTS_Database
Filter&O Typeaquery:{field:'value'} Reset Find <> More
•University
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
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
JavaScript
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>
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
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
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,
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
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
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
JavaScript
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
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
JavaScript
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
new_weather_db>db.weather_data.updateOne(<_id:ObjectId("5553a9984b02cf7151190c0")),<$inc:felevation:
{
acknowledged:true,
insertedId:null,
matchedCount:1,
modifiedCount:1,
upsertedCount:0
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