Skip to content

Instantly share code, notes, and snippets.

@debu999
Last active May 25, 2023 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debu999/159a003c9913284a4b54089c10b622bf to your computer and use it in GitHub Desktop.
Save debu999/159a003c9913284a4b54089c10b622bf to your computer and use it in GitHub Desktop.
MongoDB Crud Operations

Create a new db via mongosh or change to exisiting db.

use oreillylearning
switched to db oreillylearning
db
oreillylearning

db.books.insertOne({title: 'mastering oreilly mongoDB', isbn: 101})
db.books.find()
db.books.updateOne({isbn:101}, {$set: { price: 30}})
db.books.deleteOne({isbn: 101})
db.books.updateOne({isbn: 102}, {$set: {"testvar": "test"}}, {upsert: true})

var region="INDIA"
db.books.updateOne({isbn: 102}, {$set: {authorRegion: region}})

queryBooksByIsbn = function(isbn) { return db.books.find({isbn: isbn})}
queryBooksByIsbn(102)

Screenshot 2023-05-25 at 7 59 22 AM

bulkbookinsert = function()
{
  for(i=0;i<1000;i++)
  {
    db.books.insertOne({name: "Mongo DB Book Number" + i}) 
  }
}
< [Function: bulkbookinsert]

fastBulkBookInsert = function()
{
  var bulk = db.books.initializeUnorderedBulkOp();
  for(i=0;i<1000;i++)
  {
    bulk.insert({name: "Mongo DB Book Number" + i}) 
  }
  bulk.execute();
}
< [Function: fastBulkBookInsert]

db.bookOrders.find()
{
  _id: ObjectId("646ecc8611d51b196ad8c61e"),
  name: 'Mastering Mongodb',
  available: 99,
  isbn: 101
}

# With the following series of operations in a single bulk operation, we are adding one book to the inventory and then ordering 100 books, for a final total of 0 copies available:

var bulkOp = db.bookOrders.initializeOrderedBulkOp();

bulkOp.find({isbn: 101}).updateOne({$inc: {available : 1}});  // increment by 1

bulkOp.find({isbn: 101}).updateOne({$inc: {available : -100}});

bulkOp.execute();
db.bookOrders.find()
{
  _id: ObjectId("646ecc8611d51b196ad8c61e"),
  name: 'Mastering Mongodb',
  available: 0,
  isbn: 101
}

When executing through an ordered list of operations, MongoDB will split the operations into batches of 1000 and group these by operation
bulkWrite arguments, as shown in the following code snippet, are the series of operations we want to execute; WriteConcern (the default is again 1), and if the series of write operations should get applied in the order that they appear in the array (they will be ordered by default):

db.collection.bulkWrite([ <operation 1>, <operation 2>, ... ],
{writeConcern : <document>, ordered : <boolean> } )

The following operations are the same ones supported by bulk:

  • insertOne
  • updateOne
  • updateMany
  • deleteOne
  • deleteMany
  • replaceOne

updateOne, deleteOne, and replaceOne have matching filters; if they match more than one document, they will only operate on the first one. It’s important to design these queries so that they don’t match more than one document; otherwise, the behavior will be undefined.

Administration is generally performed on three different levels, ranging from more generic to more specific: process, collection, and index.
At the process level, there is the shutDown command to shut down the MongoDB server.

At the database level, we have the following commands:

  • dropDatabase to drop the entire database
  • listCollections to retrieve the collection names in the current database
  • copyDB or clone to clone a remote database locally
  • repairDatabase for when our database is not in a consistent state due to an unclean shutdown.

In comparison, at the collection level, the following commands are used:

  • drop: To drop a collection
  • create: To create a collection
  • renameCollection: To rename a collection
  • cloneCollection: To clone a remote collection to our local database
  • cloneCollectionAsCapped: To clone a collection into a new capped collection
  • convertToCapped: To convert a collection to a capped one.

At the index level, we can use the following commands:

  • createIndexes: To create new indexes in the current collection
  • listIndexes: To list existing indexes in the current collection
  • dropIndexes: To drop all indexes from the current collection
  • reIndex: To drop and recreate an index in the current collection

COMPACT/CURRENTOP/KILLOP/COLLMOD

Defragmentation on size compact db.runCommand ( { compact: '<collection>', force: true } ) db.currentOp() : List current running Operations in MongoDB db.runCommand( { "killOp": 1, "op": <operationId> } ) Kill the operation if needed

  • collMod helps with adding validations to collections. Below ensure in every insert we have isbn and name found so db.bookOrders.insert({isbn: 102}) will fail with message MongoBulkWriteError: Document failed validation
db.runCommand( 
{ collMod: "bookOrders",
"validator" : 
  {
    "$and" : 
    [ 
      { "isbn" : { "$exists" : true } }, 
      { "name" : { "$exists" : true  } }
    ] 
  }
})

Aggregation Framework

Screenshot 2023-05-25 at 8 50 20 AM

CREATE USER - MongoDB Auth

use admin
db.createUser({user: <adminUser>,pwd: <password>,roles: [ { role: <adminRole>, db: "admin" } ]})

Default Roles in MongoDB ordered from more powerful to least powerful (dbAdminAnyDatabase = userAdminAnyDatabase + readWriteAnyDatabase)

  • root
  • dbAdminAnyDatabase
  • userAdminAnyDatabase
  • readWriteAnyDatabase
  • readAnyDatabase
  • dbOwner
  • dbAdmin
  • userAdmin
  • readWrite
  • read

MongoDB Stable API ApiVersion=1 supports any of the following commands:

  • abortTransaction: To terminate a multi-document (also known as distributed) transaction and roll back its results.
  • aggregate: (with limitations) To execute an aggregation pipeline.
  • authenticate: To authenticate a client using the x.509 authentication mechanism.
  • count: Introduced in version 6 and available since version 5.0.9, this counts the number of documents in a collection or a view.
  • collMod: To modify view definitions or add options to a collection.
  • commitTransaction: To commit a multi-document transaction.
  • create: (with limitations) To create a collection or view.
  • createIndexes: (with limitations) To create one or more indexes in a collection.
  • delete: To remove one or more documents from a collection.
  • drop: To remove an entire collection.
  • dropDatabase: To remove an entire database.
  • dropIndexes: To remove one or more indexes from a collection.
  • endSessions: To expire specific sessions after waiting for the timeout period.
  • explain: (output may change in future versions) To get an execution query plan for MongoDB operations.
  • find: (with limitations) To execute a query against a collection.
  • findAndModify: To execute a query against a collection and modify one or more documents in the result set. getMore`: To fetch more documents in commands that use a cursor to return results in batches.
  • insert: To insert one or more documents in a collection.
  • hello: To return information about the MongoDB server. This may include primary/secondary replica set information as well as authentication method supported and other role-level information.
  • killCursors: To delete cursors that are returned from queries that return results in batches.
  • listCollections: To list collections in the database.
  • listDatabases: To list databases.
  • listIndexes: To list indexes in a collection.
  • ping: To ping a server, equivalent to the Internet Control Message Protocol (ICMP) echo request/reply.
  • refreshSessions: To update the last used time for specified sessions in order to extend their active state.
  • update: To update one or more documents in a collection.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment