Skip to content

Instantly share code, notes, and snippets.

@zahra-ove
Last active July 24, 2024 03:30
Show Gist options
  • Save zahra-ove/2b7dde375f5dd9a77f867f9a5bfd91ec to your computer and use it in GitHub Desktop.
Save zahra-ove/2b7dde375f5dd9a77f867f9a5bfd91ec to your computer and use it in GitHub Desktop.

these commands are specific to mongo shell (mongosh command):

  1. show dbs ==> shows list of all available databases

  2. use flights ==> when starting to insert data in this DB, then flights db will be created on the fly.

  3. db.flightData.insertOne({"name":"f1"})

  4. db.flightData.find(); ==> shows all data

  5. db.flightData.find().pretty(); ==> shows all data in pretty format

  6. mongoDB uses BSON (which is binary json) for storing data in database.

  7. to delete all data in flightData table: db.flightData.deleteMany({});

  8. to delete specific document in flightData table: db.flightData.deleteOne({_id: 1})

**note: in mongoDB documents, if key has no space in it then you can omit the double quotes around the key. but value of key always must sarround by double quotes.

  1. to update specific document: db.flightData.updateOne({_id:2}, {$set: {distance: 1000}})

    in flightData collection(table), find the document which has _id=2 and then update distance column value to 1000. if distance key does not exist, then it first create it and then assign the 1000 value to it.

  2. to update all documents in a collection, then: db.flightData.updateMany({}, {$set: {marker: "toDelete"}})

  3. to find all flights which have distance greater than 1000 km: db.flightData.find({distance: {$gt: 1000}}).pretty()

  4. to find first flight which has distance greater than 100 km: db.flightData.findOne({distance: {$gt: 100}})

  5. for updating a document, use updateOne or updateMany.

  6. be careful about update. this operator replace all keys of document with given key.

  7. for replacing whole content of a document with given data, it is prefered to use replaceOne.

  8. db.flightData.find() ==> return cursor object with twenty documents from collection

  9. db.flighData.find.toArray() ==> returns all documents which exist in collection.

  10. same as select in mysql, in mongoDB we have projection; which helps us to select only specific keys(columns). for example: db.flightData.find({}, {name:1})

    this query fetches all documents exist in flightData collection and just return name and _id keys. if you want to exclude _id key, then: db.flightData.find({}, {name:1, _id:0})

  11. in mongoDB we can store document in another document. we defined them as nested document.

  12. in mongoDB up until 100 levels of nesting is allowed.

  13. in mongoDB maximum size of each document is up to 16MB.

  14. nested document === embedded document

  15. suppose we have two document with this structure:

flights> db.flightData.find() [ { _id: ObjectId('6698dd248bb6ddad76149f48'), departureAirport: 'THR', arrivalAirport: 'MSHD', status: { description: 'on-time', distance: 190 } }, { _id: ObjectId('6698dd938bb6ddad76149f49'), departureAirport: 'GHT', arrivalAirport: 'LIU', distance: 1000, status: { description: 'delayed' } } ]

now we want a document which has description:delayed key. the query will be: db.flightData.find({"status.description":"delayed"})

  1. the schema means the structure of each document.

  2. mongoDB enforces no schema. Documents don't have to use the same schema inside of one collection. but it does not mean that you
    can not use same schema.

  3. for dropping database:

	>> show dbs
 >> use test
 >> db.dropDatabase
  1. to drop a collection entirely:
	>> db.flightData.drop()
  1. relationship between collections in mongoDB is in two ways:

    • nested (embedded) document
    • reference (id of related document defined as array in parent document)
  2. when using Reference for relations; for merging relations it is possible to use joining with $lookup.

    	posts: {
    		title: "sample title",
    		postComments: ['id1', 'id2']
    	}
    
    	comments: {
    		_id: 'id1',
    		name: 'sample comment'
    	}
    	
    	posts.aggregate([
    		{
    			$lookup: {
    				from: "comments",
    				localField: "postComments",
    				foreignField: "_id",
    				as: "postCommentData"
    			}
    			
    		}
    	])
    

  1. using reference method and then using lookup step from aggregate is one option but it is less perfomant than embedded document.

  2. in mongoDB we can define schema validation.

  3. important image from third season of mongo course of academind.

  1. we can set custom path for logs and where data is stored by this options when starting mongod service: mongod --dbpath C/users/data --logpath C/users/log/log.log note that, log file need file name, something like: log.log
    but for data, the directory name is enough.

  2. one of "storage options" in mongodb which is very helpful is that you can configure mongodb somehow which
    consider seperate directory for each database and insert collections of each database in its subdirectory.
    by default mongodb place all collections from all databases in data directory of mongodb.

  3. mongodb supports different storage engines, but by default it uses "wiredTiger" storage engine which is
    high performant one.

  4. we can run mongodb as a background service by using "--fork" option. --fork is only available on mac and linux. but it is possible to run mongodb as a background service in windows also ( if when installing mongodb, you checked the option of install as service) for that run cmd as adminstrator and type: net start mongod

in linux and macOS: mongo --fork --logpath C/users/log/log.log note that when using --fork option, it is necessary to determine the log path.

and then how could we stop this service? in windows -> there is two way: way1: in cmd -> net stop mongod way2: connect to mongodb server by shell and run these commands: use admin db.shutdownServer()

in linux and macOS: connect to mongodb server by shell and run these commands: use admin db.shutdownServer()

  1. it is possible to define a config file for mongodb and define every possible config like
    data storage path and place of log file in it. then when running mongodb you must determine the path of config file, something like:
    mongod --f /{path of config file}/mongo.cfg` in this example I named this config file as "mongo.cfg" you can also name it something like: "mogo.conf" and place it anywhere you want.

38.by using "MongoDB Compass" you can explore data visually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment