Skip to main content

MongoDB — Queries at a Glance — 2


Types of MongoDB Queries at a Glance.
Run the following one by one in the terminal of the folder where databases is stored.
  1. mongo
    • Opens mongo shell
  2. show dbs
    • displays all databases
  3. use <database name>
    • used to get a database active
  4. db.<collection>.find().pretty()
    • show cursor of all data from a collection
  5. db.<collection>.find({<field>: <integer>}).pretty()
    • show cursor of data from a collection where <field> is <integer> value
  6. db.<collection>.find({<field>: {$gt: <integer>}}).pretty()
    • show cursor of data from a collection where <field> is greater than <integer> value
  7. db.<collection>.find({<field>: {$gte: <integer>}}).pretty()
    • show cursor of data from a collection where <field> is greater than or equal to <integer> value
  8. db.<collection>.findOne({<field>: <integer>})
    • show first document with <field> equal to <integer> value mentioned
  9. db.<collection>.find({<field>: {$ne: <integer>}}).pretty()
    • show cursor of data from a collection where <field> is not equal to <integer> value
  10. db.<collection>.find({<field>: {$lt: <integer>}}).pretty()
    • show cursor of data from a collection where <field> is less than <integer> value
  11. db.<collection>.find({<field>: {$lte: <integer>}}).pretty()
    • show cursor of data from a collection where <field> is less than or equal to <integer> value
  12. db.<collection>.find({"<field>.<embeded field>": {$gt: <integer>}}).pretty()
    • show cursor of data where <embeded field> of <field> is greater than <integer> value from a collection
  13. db.<collection>.find({<array field>: <value>}).pretty()
    • show cursor of data from a collection where <array field> has <value> in it
  14. db.<collection>.find({<array field>: [<value>]}).pretty()
    • show cursor of data from a collection where <array field> has exactly [<value>] in it
  15. db.<collection>.find({<field>: {$in: [<value1>, <value2>]}}).pretty()
    • show cursor of data from a collection where <field> either has value <value1> or <value2>
  16. db.<collection>.find({<field>: {$nin: [<value1>, <value2>]}}).pretty()
    • show cursor of data from a collection where <field> has value anything but <value1> or <value2>
  17. db.<collection>.find({<field>: {$lt: <value>}}).count()
    • show count of documents from a collection where <field> has value less than <value>
  18. db.<collection>.find({$or: [{<field1>: {$lt: <value1>}}, {<field1>: {$gt: <value2>}, {<field2>: {$gt: <value3>}]}).pretty()
    • show cursor of documents from a collection where <field1> has value less than <value1> or <field1> has value less than <value2> or <field2> has value greater than <value3>
  19. db.<collection>.find({$nor: [{<field1>: {$lt: <value1>}}, {<field1>: {$gt: <value2>}, {<field2>: {$gt: <value3>}]}).pretty()
    • show cursor of documents from a collection where <field1> does not have value less than <value1> or <field1> does not have value less than <value2> or <field2> does not have value greater than <value3>
    • It is the opposite of or
    • If we take count of the two queries above, if the first one returns x, the second one will return (count of all documents – x)
  20. db.<collection>.find({$and: [{<field1>: {$lt: <value1>}}, {<field2>: {$lt: <value2>}]}).pretty()
    • show cursor of documents from a collection where <field1> has value less than <value1> and <field2> has value less than <value2>
  21. db.<collection>.find({<field1>: {$lt: <value1>}, <field2>: {$lt: <value2>}}).pretty()
    • The previous query can be written in this form too
  22. db.<collection>.find({$and: [{<field1>: <value1>}, {<field1>: <value2>}]}).pretty()
    • This is an example where using 4and is a must
  23. db.<collection>.find({<field>: {$not: {$eq: 60}}}).count()
    • usage of $not
  24. db.<collection>.find({<field>: {$ne: 60}}).count()
    • The previous query can also be written with $ne
  25. db.<collection>.find({<field>: {$exists: true}}).pretty()
    • Returns all documents where <filed> is defined
  26. db.<collection>.find({<field>: {$exists: false}}).pretty()
    • Returns all documents where <field> is not defined
  27. db.<collection>.find({<field>: {$exists: true, $ne: null}}).pretty()
    • $exists can be combined with other comparison operators
    • The above example returns cursor to documents where field exist and has a valid value
  28. db.<collection>.find({<field>: {$type: "number"}}).pretty()
    1. returns cursor to documents where fields has value of type number
  29. db.<collection>.find({<field>: {$type: "double"}}).pretty()
    • All integers will also be shown since shell only knows doubles
  30. db.<collection>.find({<field>: {$type: ["double", "string"]}}).pretty()
    • returns cursor to documents where field type is double or string
  31. db.<collection>.find({<field>: {$regex: /<key>/}}).pretty()

  32. When to use $elemMatch?
    • {
        _id: 1,
        name: { first: 'John', last: 'Backus' },
        birth: new Date('Dec 03, 1924'),
        death: new Date('Mar 17, 2007'),
        contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
        awards: [
                  { award: 'National Medal',
                    year: 1975,
                    by: 'NSF' },
                  { award: 'Turing Award',
                    year: 1977,
                    by: 'ACM' }
                ]
      }
    • Problem: Find the person who has award 'Nation Medal' and must be awarded in year 1975
    • Solution:
    • db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})
    • $elemMatch allows you to match more than one component within the same array element.
    • Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.
  33. When to use $expr and $cond?
    • {
       "_id": 1,
       "volume": 89,
       "target": 80
      }
      {
      "_id": 2,
      "volume": 200,
      "target": 117
      }
      {
      "_id": 3,
      "volume": 100,
      "target": 117
      }
    • Problem: Find documents where value of volume field is greater than value of target field
    • Solution:
    • db.<collection>.find({$expr: {$gt: ["$volume", "$target"]}}).pretty()
    • Problem: Volume greater than 190 and difference between Volume and Target to be a minimum of 10
    • Solution:
    • db.<collection>.find({$expr: {$gt: [{$cond: {if: {$gte: ["$volume", 190]}, then: {$subtract: ["$volume", 10]}, else: "$volume"}}, "$target"]}}).pretty()
  34. How to import data from json file to MongoDB?
    • mongoimport <file name>.json -d <databse name> -c <collection name> --drop --jsonArray
  35. db.<collection>.find({"<array>.<field of object>": <value>}).pretty()
    • returns cursor to group of documents where in the <array>, one of the <object>'s <field> has the <value>
  36. db.<collection>.find({hobbies: {$size: 3}}).pretty()
    • Only exact matches supported
  37. Find the count of documents in a collection where a field's first subfield's value is "Value1" and the field's second subfield's value is greater than or equal to Value2.
    • Wrong way: db.<collection>.find({$and: [{"<field>.<subfield>": "Value1"}, {"<field>.<subfield>": {$gte: <Value2>}}]}).count()
      • Output: 2
    • Right way: db.<collection>.find({<field>: {$elemMatch: {<subfield1>: "<Value1>", <subfield2>: {$gte: Value2}}}}).pretty()
  38. Find documents in a collection where a field has n number of elements in its array
    • db.<collection>.find({<field>: {$size: <n>}}).pretty()
  39. Find within an embedded document
    • db.<collection>.find({"<field>.<subfield>": "Value"}).pretty()
  40. Check if one value of an array has two or more conditions
    • Right way: db.<collection>.find({field: {$elemMatch: {$gt: 8, $lt: 10}}}).pretty()
    • Wrong way: db.<collection>.find({field: {$and: [{$gt: 8, $lt: 10}]}}).pretty()
  41. Sorting Cursor - Sort entire collection with one field in ascending order and within that sort by another field in descending order
    • db.<collection>.find().sort({"<field1.subfield>": 1, <field2>: -1}).pretty()
  42. Skip and Limit
    • db.<collection>.find().skip(10).limit(20).pretty()
      • Skip skips the number of documents and then fetches
      • Limit limits the number of documents it fetches
      • If sort is used, skip and limit always applies on sorted result
  43. Projection — Get result with only specified fields and not all fields
      • db.<collection>.find(<filer>, <projection>)
    • db.<collection>.find({}, {<field1>: 1, "<field2>.<subfield>": 1})
      • Id is always included in the result
    • db.<collection>.find({}, {<field1>: 1, "<field2>.<subfield>": 1, _id: 0})
      • To exclude id, add _id: 0 to the query explicitly
  44. Filter and Projection
    • db.<collection>.find({<field>: "Value1"}, {"<field>.$": 1}).pretty()
    • db.<collection>.find({<field>: {$all: ["Value1", "Value2"]}}, {"<field>.$": 1}).pretty()
    • db.<collection>.find({<field>: "Value1"}, {<field>: {$elemMatch: {$eq: "Value2"}}}).pretty()
  45. Project from and to in an array
    • db.<collection>.find({"<field1>.<subfield>": {$gt: <n>}}, {<arrayfield2>: {$slice: [1,2]}, <field3>: 1}).pretty()
      • This drops the element at 0 index and displays elements from index 1 to 2

Comments

Popular posts from this blog

Python - Mathematical Functions - Hexadecimal, Binary, Exponential, Absolute, Round

🐍 Some mathematical functions are in-built in python. Here are some of them. Convert Decimal to Hexadecimal hex(246) Output: '0xf6' hex(512) Output: '0x200' 0x is prefix to all hexadecimal numbers in output. The number after 0x is the hexadecimal value. Convert Decimal to Binary bin(1234) Output: '0b10011010010' bin(246) Output: '0b11110110' bin(512) Output: '0b1000000000' Exponential Function pow() function is similar to num1**num2, but it comes useful when you want to execute (num1**num2)%num3. Passing three arguments to pow(), does this. pow(3,4) Output: 81 This works just like 3**4 pow(3,4,5) Output: 1 But this, works equivalent to (3**4)%5. Either of the two ways can be used. At this point I feel (3**4)%5 is better, as anybody reading the code will understand what is being done immediately. While with pow(2,3,4), the person may have to refer to documentation to understand how this function works. Absolute Value The function abs() is used ...

Two Ways of rendering in React Examples

Two Ways of rendering in React Examples 1 - Render twice HTML < div id = "p1" ></ div > < div id = "p2" ></ div > CSS . person { display : inline - block ; margin : 10px ; border : 1px solid # eee ; box - shadow : 0 2px 2px # ccc ; } JAVASCRIPT (Babel) function Person ( props ) { return ( < div className = ' person "> < h1 >{ props . name }</ h1 > < p > Age :{ props . age }</ p > </ div > ); } ReactDOM . render (< Person name = "VK" age = "29" />, document . querySselector ( '#p1' )); ReactDOM . render (< Person name = "HK" age = "28" />, document . querySselector ( '#p2' )); 2 Render all at once HTML < div id = "app" ></ div > CSS . person { display : inline - block ; margin : 1...

Binary Tree Traversal in Python - In Order, Pre Order, Post Order

Binary Tree Traversal in Python - In Order, Pre Order, Post Order Run the code here to see output:  https://repl.it/@VinitKhandelwal/iterative-traversal-of-binary-tree # Node Class to Create Object of Nodes class Node (): def __init__ ( self , value , left= None , right= None ): self .value = value self .left = left self .right = right # Creation of a Binary Tree class BinaryTree (): def __init__ ( self , mylist ): self .mylist = mylist self .root=Node ( None ) for value in self .mylist : self .curr= self .root self ._add ( value ) def _add ( self , value ): if self .curr.value == None : self .curr.value = value else : if self .curr.value > value : if self .curr.left == None : self .curr.left = Node ( value ) else : self .curr = self .curr.left self ._add ( value ) else : if self...