Guest User

Untitled

a guest
Sep 11th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.63 KB | None | 0 0
  1. Purpose of NOsql selection
  2. ==========================
  3. Ease of scaling
  4. a document can hold complex hiararchical record within a single document but but row cant in relational database
  5. developers who came from object oriented languages and familiar with Arrays, objects can easily work
  6.  
  7.  
  8. Mongodb Features
  9. ================
  10. indexing
  11. aggregation
  12. special collection types
  13. sessions
  14. fixed size collections
  15. file storage
  16.  
  17.  
  18. fixed size collections
  19. ----------------------
  20.  
  21. if user is aware about data size to be stored then he/she can create capped collection. it
  22. will give performance by occupying less space.
  23.  
  24. following will limit maximum no of records as 3000
  25.  
  26. db.createCollection("cappedCollectionForCache",{capped:true,size:20000,max:3000})
  27.  
  28.  
  29.  
  30. case sensitive
  31. ==============
  32. yes it is
  33.  
  34.  
  35. Querying Operators
  36. ==================
  37.  
  38. Insert
  39. -----
  40.  
  41. db.foo.insert({"bar" : "baz"})
  42.  
  43. Batch Insert
  44. ------------
  45.  
  46. db.foo.batchInsert([{"_id" : 0}, {"_id" : 1}, {"_id" : 2}])
  47.  
  48.  
  49. Remove
  50. ------
  51.  
  52. db.foo.remove()
  53.  
  54. db.mailing.list.remove({"opt-out" : true})
  55.  
  56.  
  57. Find One
  58. --------
  59.  
  60. db.users.findOne({"name" : "joe"});
  61.  
  62.  
  63. find
  64. ----
  65.  
  66. find() will return all rows
  67.  
  68.  
  69. db.people.find()
  70.  
  71.  
  72. update
  73. ------
  74.  
  75.  
  76. db.people.update({"_id" : ObjectId("4b2b9f67a1f631733d917a7c")}, joe)
  77.  
  78.  
  79. update value
  80.  
  81. {
  82. "_id" : ObjectId("4b253b067525f35f94b60a31"),
  83. "url" : "www.example.com",
  84. "pageviews" : 52
  85. }
  86.  
  87.  
  88. db.analytics.update({"url" : "www.example.com"},
  89. {"$inc" : {"pageviews" : 1}})
  90.  
  91. then output would be
  92.  
  93. {
  94. "_id" : ObjectId("4b253b067525f35f94b60a31"),
  95. "url" : "www.example.com",
  96. "pageviews" : 53
  97. }
  98.  
  99.  
  100. Aggregate
  101. ---------
  102.  
  103. Group by and Calculate a Sum
  104.  
  105. { _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
  106. { _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
  107. { _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
  108. { _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
  109. { _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }
  110.  
  111.  
  112. db.orders.aggregate([
  113. { $match: { status: "A" } },
  114. { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
  115. { $sort: { total: -1 } }
  116. ])
  117.  
  118.  
  119. output
  120. ------
  121.  
  122. { "_id" : "xyz1", "total" : 100 }
  123. { "_id" : "abc1", "total" : 75 }
  124.  
  125.  
  126.  
  127. Aggregation Example 2
  128. ---------------------
  129.  
  130. db.transactions.aggregate([
  131. {
  132. $match: {
  133. transactionDate: {
  134. $gte: ISODate("2017-01-01T00:00:00.000Z"),
  135. $lt: ISODate("2017-01-31T23:59:59.000Z")
  136. }
  137. }
  138. }, {
  139. $group: {
  140. _id: null,
  141. total: {
  142. $sum: "$amount"
  143. },
  144. average_transaction_amount: {
  145. $avg: "$amount"
  146. },
  147. min_transaction_amount: {
  148. $min: "$amount"
  149. },
  150. max_transaction_amount: {
  151. $max: "$amount"
  152. }
  153. }
  154. }
  155. ]);
  156.  
  157.  
  158. Transformations used in aggregation pipeline
  159. --------------------------------------------
  160.  
  161. $geoNear: outputs documents in order of nearest to farthest from a specified point
  162.  
  163. $match: filters input record set by any given expressions
  164.  
  165. $project: creates a resultset with a subset of input fields or computed fields
  166.  
  167. $redact: restricts the contents of the documents based on information from the document
  168.  
  169. $unwind: takes an array field with n elements from a document and returns n documents with each element added to each document as a field replacing that array
  170.  
  171. $group: groups by one or more columns and perform aggregations on other columns
  172.  
  173. $limit: picks first n documents from input sets (useful for percentile calculations, etc.)
  174.  
  175. $skip: ignores first n documents from input set
  176.  
  177. $sort: sorts all input documents as per the object given
  178.  
  179. $out: takes all the documents returned from previous stage and writes them to a collection
  180.  
  181.  
  182. Expressions used in aggregation
  183. -------------------------------
  184.  
  185.  
  186. $sum Summates the defined values from all the documents in a collection
  187. $avg Calculates the average values from all the documents in a collection
  188. $min Return the minimum of all values of documents in a collection
  189. $max Return the maximum of all values of documents in a collection
  190. $addToSet Inserts values to an array but no duplicates in the resulting document
  191. $push Inserts values to an array in the resulting document
  192. $first Returns the first document from the source document
  193. $last Returns the last document from the source document
  194.  
  195.  
  196.  
  197.  
  198. add new property with $set
  199. --------------------------
  200.  
  201. db.users.update({"_id" : ObjectId("4b253b067525f35f94b60a31")},
  202. ... {"$set" : {"favorite book" : "War and Peace"}})
  203.  
  204.  
  205. set value to the nested property
  206. --------------------------------
  207.  
  208. db.blog.posts.update({"author.name" : "joe"},
  209. ... {"$set" : {"author.name" : "joe schmoe"}})
  210.  
  211.  
  212.  
  213.  
  214. remove property with $unset
  215. ---------------------------
  216.  
  217. db.users.update({"name" : "joe"},
  218. ... {"$unset" : {"favorite book" : 1}})
  219.  
  220.  
  221. Array modifiers
  222. ---------------
  223.  
  224. db.blog.posts.findOne()
  225. {
  226. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  227. "title" : "A blog post",
  228. "content" : "...",
  229. "comments" : [
  230. {
  231. "name" : "joe",
  232. "email" : "[email protected]",
  233. "content" : "nice post."
  234. }
  235. ]
  236. }
  237.  
  238.  
  239. here use $push to add another comment
  240.  
  241. db.blog.posts.update({"title" : "A blog post"},
  242. ... {"$push" : {"comments" :
  243. ... {"name" : "bob", "email" : "[email protected]",
  244. ... "content" : "good post."}}})
  245.  
  246.  
  247. output
  248.  
  249.  
  250. "comments" : [
  251. {
  252. "name" : "joe",
  253. "email" : "[email protected]",
  254. "content" : "nice post."
  255. },
  256. {
  257. "name" : "bob",
  258. "email" : "[email protected]",
  259. "content" : "good post."
  260. }
  261. ]
  262.  
  263.  
  264. Prevent duplicates
  265. ------------------
  266.  
  267. db.users.findOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")})
  268. {
  269. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  270. "username" : "joe",
  271. "emails" : [
  272. ]
  273. }
  274.  
  275.  
  276. db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")},
  277. ... {"$addToSet" : {"emails" : "[email protected]"}})
  278.  
  279.  
  280.  
  281. output
  282. ------
  283.  
  284.  
  285. db.users.findOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")})
  286. {
  287. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  288. "username" : "joe",
  289. "emails" : [
  290. ]
  291. }
  292.  
  293.  
  294. prevent duplicates and add multiple values
  295. -------------------------------------------
  296.  
  297. db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")}, {"$addToSet" :
  298. ... {"emails" : {"$each" :
  299.  
  300.  
  301. output
  302. ------
  303.  
  304. {
  305. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  306. "username" : "joe",
  307. "emails" : [
  308. }
  309.  
  310.  
  311.  
  312. Removing Elements
  313. ------------------
  314.  
  315. db.lists.insert({"todo" : ["dishes", "laundry", "dry cleaning"]})
  316.  
  317. db.lists.update({}, {"$pull" : {"todo" : "laundry"}})
  318.  
  319. output
  320. ------
  321.  
  322. db.lists.find()
  323. {
  324. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  325. "todo" : [
  326. "dishes",
  327. "dry cleaning"
  328. ]
  329. }
  330.  
  331.  
  332. Note : $pull will remove all matching elements for example [1, 1, 2, 1] if pull 1 means remaining is 2 only.
  333.  
  334.  
  335. distinct
  336. --------
  337.  
  338. { "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
  339. { "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
  340. { "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
  341. { "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
  342.  
  343.  
  344. db.inventory.distinct( "dept" )
  345.  
  346.  
  347. output
  348. ------
  349.  
  350. { "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
  351. { "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
  352.  
  353.  
  354.  
  355. Positional array modifiers
  356. --------------------------
  357.  
  358. ...
  359. "comments" : [
  360. {
  361. "comment" : "good post",
  362. "author" : "John",
  363. "votes" : 0
  364. },
  365. {
  366. "comment" : "i thought it was too short",
  367. "author" : "Claire",
  368. "votes" : 3
  369. },
  370. {
  371. "comment" : "free watches",
  372. "author" : "Alice",
  373. "votes" : -1
  374. }
  375. ]
  376.  
  377.  
  378. If we want to increment the number of votes for the first comment, we can say the
  379. following:
  380. > db.blog.update({"post" : post_id},
  381. ... {"$inc" : {"comments.0.votes" : 1}})
  382.  
  383.  
  384. if we dont know the index use $ operator
  385.  
  386.  
  387. db.blog.update({"comments.author" : "John"},
  388. ... {"$set" : {"comments.$.author" : "Jim"}})
  389.  
  390.  
  391.  
  392. findAndModify Example
  393. ---------------------
  394.  
  395. ps = db.runCommand({"findAndModify" : "processes",
  396. ... "query" : {"status" : "READY"},
  397. ... "sort" : {"priority" : -1},
  398. ... "update" : {"$set" : {"status" : "RUNNING"}})
  399.  
  400. we can also remove a field using this,
  401.  
  402. db.runCommand({"findAndModify" : "processes",
  403. "query" : {"status" : "READY"},
  404. "sort" : {"priority" : -1},
  405. "remove" : true}).value
  406.  
  407.  
  408.  
  409. specifies keys to return in find
  410. ---------------------------------
  411.  
  412. db.users.find({}, {"username" : 1, "email" : 1})
  413.  
  414.  
  415. prevent id from beign return
  416. -----------------------------
  417.  
  418. db.users.find({}, {"username" : 1, "_id" : 0})
  419.  
  420.  
  421. conditonal querying example
  422. ---------------------------
  423.  
  424. db.users.find({}, {"username" : 1, "_id" : 0})
  425.  
  426.  
  427. > start = new Date("01/01/2007")
  428. > db.users.find({"registered" : {"$lt" : start}})
  429.  
  430. db.raffle.find({"ticket_no" : {"$in" : [725, 542, 390]}})
  431.  
  432. db.raffle.find({"ticket_no" : {"$nin" : [725, 542, 390]}})
  433.  
  434. db.raffle.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]})
  435.  
  436.  
  437. $or can contain nested conditions
  438.  
  439. db.raffle.find({"$or" : [{"ticket_no" : {"$in" : [725, 542, 390]}},
  440. {"winner" : true}]})
  441.  
  442. db.users.find({"id_num" : {"$mod" : [5, 1]}})
  443.  
  444. db.users.find({"id_num" : {"$not" : {"$mod" : [5, 1]}}})
  445.  
  446.  
  447. type specific queries
  448. ---------------------
  449.  
  450. db.c.find({"y" : null})
  451.  
  452.  
  453. Regular Expressions
  454. --------------------
  455.  
  456. db.users.find({"name" : /joey?/i})
  457.  
  458.  
  459. Querying Arrays
  460. ---------------
  461.  
  462. db.food.insert({"fruit" : ["apple", "banana", "peach"]})
  463.  
  464. db.food.find({"fruit" : "banana"})
  465.  
  466.  
  467. find all rows contain both using $all
  468. -------------------------------------
  469.  
  470. db.food.find({fruit : {$all : ["apple", "banana"]}})
  471.  
  472.  
  473. query value with given size $size
  474. ---------------------------------
  475.  
  476. db.food.find({"fruit" : {"$size" : 3}})
  477.  
  478.  
  479.  
  480. $slice
  481. ------
  482.  
  483. db.blog.posts.findOne(criteria, {"comments" : {"$slice" : 10}})
  484.  
  485. we can use below for last ten comments
  486.  
  487. db.blog.posts.findOne(criteria, {"comments" : {"$slice" : -10}})
  488.  
  489.  
  490. following will be very useful for pagination
  491.  
  492. db.blog.posts.findOne(criteria, {"comments" : {"$slice" : [23, 10]}})
  493.  
  494.  
  495. Querying on Embedded docs
  496. -------------------------
  497.  
  498. db.people.find({"name.first" : "Joe", "name.last" : "Schmoe"})
  499.  
  500.  
  501. sort using sot()
  502. ----------------
  503.  
  504. db.c.find().sort({username : 1, age : -1})
  505.  
  506.  
  507.  
  508. index
  509. -----
  510.  
  511. db.users.ensureIndex({"username" : 1})
  512.  
  513.  
  514. compund index
  515. -------------
  516.  
  517. db.users.find().sort({"age" : 1, "username" : 1})
  518.  
  519.  
  520. indexing object
  521. --------------
  522.  
  523. db.users.ensureIndex({"loc.city" : 1})
  524.  
  525. indexing specific Array
  526. -----------------------
  527.  
  528. db.blog.ensureIndex({"comments.10.votes": 1})
  529.  
  530.  
  531. unique index
  532. ------------
  533.  
  534. db.users.ensureIndex({"username" : 1}, {"unique" : true})
  535.  
  536.  
  537. removing or dropping duplicates names by index
  538. ----------------------------------------------
  539.  
  540. db.people.ensureIndex({"username" : 1}, {"unique" : true, "dropDups" : true})
  541.  
  542.  
  543. select not in list
  544. ------------------
  545.  
  546. db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
  547.  
  548. This query will select all documents in the inventory collection where the qty field value does not equal 5 nor 15. The selected documents will include those documents that do not contain the qty field.
  549.  
  550.  
  551. $nor
  552. ---
  553.  
  554. db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ] } )
  555.  
  556. This query will return all documents that:
  557.  
  558. contain the price field whose value is not equal to 1.99 and contain the sale field whose value is not equal to true or
  559. contain the price field whose value is not equal to 1.99 but do not contain the sale field or
  560. do not contain the price field but contain the sale field whose value is not equal to true or
  561. do not contain the price field and do not contain the sale field
  562. $nor and Additional Comparisons
  563.  
  564.  
  565. $exists
  566. -------
  567.  
  568. db.inventory.find( { qty: { $exists: true, $nin: [ 5, 15 ] } } )
  569.  
  570. This query will select all documents in the inventory collection where the qty field exists and its value does not equal 5 or 15.
  571.  
  572.  
  573. $type
  574. -----
  575.  
  576. db.grades.insertMany(
  577. [
  578. { "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 },
  579. { "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" },
  580. { "_id" : 3, name : "Cathy Hart", classAverage: "94.06" },
  581. { "_id" : 4, name : "Drew Williams" , classAverage : 93 }
  582. ]
  583. )
  584.  
  585.  
  586. db.grades.find( { "classAverage" : { $type : [ "string" , "double" ] } } );
  587.  
  588. output
  589. ------
  590. { "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 }
  591. { "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" }
  592. { "_id" : 3, name : "Cathy Hart", classAverage: "94.06" }
  593.  
  594.  
  595.  
  596. Application design
  597. ------------------
  598.  
  599. Two kinds of design
  600.  
  601. 1 Embedding
  602. best for small documents
  603. best for data changing less often
  604. best for where need fast reads
  605. 2 Reference
  606. best for large documents
  607. best for where need fast writes
Add Comment
Please, Sign In to add comment