Skip to content

Instantly share code, notes, and snippets.

@vipul43
Last active May 11, 2021 06:11
Show Gist options
  • Save vipul43/6b6b8572254a14453ee76840d645e18f to your computer and use it in GitHub Desktop.
Save vipul43/6b6b8572254a14453ee76840d645e18f to your computer and use it in GitHub Desktop.
first experiment with mongo db shell

MONGO DB SHELL COMMANDS

MongoDB connection: mongodb://127.0.0.1:27017/


  • show dbs
  • db
  • use <databasename>
  • show collections
  • db.createCollection{'<collectionname>'}
     db.<collectionname>.insertOne({
     id: '001',
     name: 'Charlize Theron',
     age: 45,
     gender: 'female',
     profession: ['actress', 'producer'],
     spouse: [{name: 'Craig Bierko'}, {name: 'Stephan Jenkins'}, {name: 'Stuart Townsend'}, {name: 'Sean Penn'}],
     date_of_creation: Date()})
     db.<collectionname>.insertMany([
     {
       id: '002',
       name: 'Nicole Kidman',
       age: 53,
       gender: 'female',
       profession: [
         'actress', 'producer', 'singer'],
       spouse : [{name: 'Tom Cruise'}, {name: 'Keith Urban'}],
       date_of_creation: Date()
     },
     {
       id: '003',
       name: 'Margot Robbie',
       age: 30,
       gender: 'female',
       professsion: ['actress', 'producer'],
     spouse: [{name: 'Tom Ackerley'}],
     date_of_creation: Date()
     },
     {
       id: '004',
       name: 'Tom Hardy',
       age: 43,
       gender: 'male',
       profession: ['actor', 'producer', 'model'],
       spouse: [{name: 'Sarah Ward'}, {name: 'Charlotte Riley'}],
       date_of_creation: Date()
     },
     {
       id: '005',
       name: 'Scarlett Johansson',
       age: 36,
       gender: 'female',
       profession: ['actress', 'singer'],
       spouse: [{name: 'Ryan Reynolds'}, {name: 'Romain Dauriac'}, {name: 'Colin Jost'}],
       date_of_creation: Date()
     }
     ])
  • db.<collectionname>.find() -> return all the records of collection
  • db.<collectioname>.find({ age: { $gt: 40 } }) -> filter the results according to age field "greater than" 40
  • db.<collectionname>.find({age: {$lte: 40}}).pretty() -> filter the results according to age field "less than or equal" to 40
db.<collectionname>.update({ name: 'Margot Robbie' }, 
                           { 
                              $set: {
                                   date_of_creation: Date(),
                                   age:30
                              }
                           })

-> update one record that matches the condition according to the given rule above

db.<collectionname>.updateMany({name: "Scarlett Johansson"}, 
                               {
                                   $set: {
                                        age: 36         
                                   } 
                               })

-> update all records that match the condition according to given rule above

  • db.<collectionname>.find().sort({name:1}).pretty() -> sorting name field in ascending order
  • db.<collectionname>.find().sort({name:-1}).pretty() -> sorting name field in descending order
  • db.<collectionname>.find().count() -> counting the records returned by find
  • db.<collectionname>.find().limit(2) -> limit the record results of find to 2
db.<collectionname>.replaceOne({name: 'Scarlett Johansson'},
                               {
                                   id: '005',
                                   name: "Scarlett Johansson",
                                   age: "00"
                               })

-> replacing one record with new record which is given in the statement above

  • db.<collectionname>.remove({name: 'Scarlett Johansson'}) -> deleting all the querues that match the condition
db.<collectionname>.remove({date_of_creation: 'Mon May 10 2021 13:54:46 GMT+0530 (IST)'}, 
                           {justOne: true})

-> deleting one query that matches the conditon

  • db.<collectionname>.find({gender: {$regex: /^male/}}).count() -> case sensitive string starting match
  • db.<collectionname>.find({gender: {$regex: /male/}}) -> case sensitive substring match
  • db.posts.find({date_of_creation: {$regex: /\(IST\)$/}}) -> case sensitive string ending match
  • db.posts.find({date_of_creation: {$regex: /\(ist\)$/i}}) -> case insensitive match
db.posts.find(
          {spouse: 
               {$elemMatch : 
                    {name: "Tom Ackerley"} 
               } 
          } )

-> find results according to given condition from nested records

  • db.posts.update({name: "Margot Robbie"}, {$rename: { 'professsion': 'profession'}}) -> renaming field names
  • db.posts.find({profession: {$in: ['actress']}}) -> if atleast one value of profession array is present in the given array, the that corresponding record is returned

  • $ mongoimport --db <databasename> --collection <collectionname> --file <filepath>
var allKeys = {}
db.<collectionname>.find().forEach(function(doc){Object.keys(doc).forEach(function(key){allKeys[key]=1})})
allKeys

-> creating an empty json object and filling it with keys of collection as keys and values as 1, printing json object

  • db.restaurants.find({cuisine: {$regex: /hawaiian/i}, 'grades.grade': 'A'}) or db.restaurants.find({cuisine: {$regex: /hawaiian/i}, 'grades.grade':{ $in : ['A']}}) -> find restaurants with Hawaiian cuisine and grade A
var cuis = {}
db.<collectionname>.find().forEach(function(doc) {cuis[doc.cuisine]=0})
db.<collectionname>.find().forEach(function(doc) {cuis[doc.cuisine]+=1})
cuis

-> get all cuisine and number of restaurants frequency, filter greater than 100 from frequency

  • db.restaurants.aggregate([{$sortByCount:"$cuisine"},{$match:{count:{$gt:100}}}]) -> to return number of restaurants corresponding to cuisine with more than 100 restaurants
  • db.restaurants.aggregate([{$sortByCount:"$cuisine"}]) -> to return number of restaurants corresponsing to each cuisine in sorted order, such that highest number of cuisines appear first

Misc

  • db.restaurants.updateMany({}, { $set: { date_of_modification: new Date() } }) -> to add a new field to existing collection
  • db.restaurants.updateMany({}, { $unset: { date_of_modification: "" } }) -> to delete an existing field from collection
  • db.restaurants_k.drop() -> to delete an existing collection
  • db.restaurants.find({}, {cuisine:1, name:1, _id:0}) -> projection operation onto fields cuisine and name
  • db.restaurants.find({cuisine: 'American'}, {cuisine:1, name:1, _id:0}) -> selection operation in the field cuisine and then projection operation
  • db.restaurants.find({ cuisine: { $ne: "American" } }) -> selection operation in the field cuisine
  • db.restaurants.find({$and: [{"grades.grade": {$eq: "A"}}, {"grades.grade": {$ne: "A"}}]}) -> and/or operation
  • db.restaurants.find({"grades.grade": {$eq: "A", $ne: "A"}}) -> chained constraints
  • db.restaurants.count() -> count operation
  • db.restaurants.aggregate([{$group: {_id: "$cuisine"}}]) -> group according to a field
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment