Using Mongosh :

Pasted image 20240212213317.png


use natours-test
show dbs

Inserting :

// db is the currently used database, tours is the collection in which we want to insert the documents in.
// we can actually simply pass a JavaScript object in the inserMany(...), it'll then convert it into JSON and BSON

// insertMany(...) expects an array of documents
// insertOne(...) expects a single document

db.tours.insertOne({name: "The Forest Hiker", price: 297, rating: 4.7 })
  • MongoDB documents are very flexible, so they do not all have to have the same structure. Hence, we can have different fields in different documents. (See ss below for more clarification)
db.tours.insertMany([{ name: "The Sea Explorer", price: 497, rating: 4.8 }, { name: "The Snow Adventurer", price: 997, rating: 4.9, difficulty: "easy" }])
  • Pasted image 20240217130639.png

Finding :

Pasted image 20240214202435.png

Pasted image 20240214202550.png

// to find the storage path : 
db.adminCommand("getCmdLineOpts").parsed.storage.dbPath

Pasted image 20240214203144.png

Searching :

Pasted image 20240217204533.png

  • Pasted image 20240217204552.png
    • Here we pass in the search criteria as an object.
  • To find tours which have a price less below 500 :
    • Pasted image 20240217205204.png
    • here $lte means <= :
  • Using multiple parameters for searching :
    • AND QUERY :
      • Pasted image 20240217205921.png
    • OR QUERY :
      • Pasted image 20240217210410.png
  • Projection of only specific fields in the output of the search :
    • Pasted image 20240217212309.png
      • Setting name: 1 means that we only want name to appear. Similarly, setting a field to 0 means that we do not that field to appear.

Updating Documents :

  • We have updateOne and updateMany, now how does updateMany work ? First we need to select the objects that we need to update then we have to pass in the data that should be updated.
  • So the first argument is basically a filter object.
  • Pasted image 20240219001750.png
  • If we have multiple queries that are selected then updateOne will only update the first matched document.

Adding a new field using update query :
Pasted image 20240219002412.png

  • a new field premium has now been added to the last document
  • For completely replacing the content of a document we can make use of the replaceOne function. It works the same way as updateOne does, but it replaces the entire document instead.

Deleting Documents :

Pasted image 20240219003420.png


Mongoose Queries :

Pasted image 20240302200224.png

  • ! NOTE :
    Pasted image 20240302200517.png
    The Model.prototype in JavaScript refers to an object created of a class.