Guest User

Untitled

a guest
Sep 11th, 2018
135
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" : "joe@example.com",
  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" : "bob@example.com",
  244. ... "content" : "good post."}}})
  245.  
  246.  
  247. output
  248.  
  249.  
  250. "comments" : [
  251. {
  252. "name" : "joe",
  253. "email" : "joe@example.com",
  254. "content" : "nice post."
  255. },
  256. {
  257. "name" : "bob",
  258. "email" : "bob@example.com",
  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. "joe@example.com",
  273. "joe@gmail.com",
  274. "joe@yahoo.com",
  275. ]
  276. }
  277.  
  278.  
  279. db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")},
  280. ... {"$addToSet" : {"emails" : "joe@hotmail.com"}})
  281.  
  282.  
  283.  
  284. output
  285. ------
  286.  
  287.  
  288. db.users.findOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")})
  289. {
  290. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  291. "username" : "joe",
  292. "emails" : [
  293. "joe@example.com",
  294. "joe@gmail.com",
  295. "joe@yahoo.com",
  296. "joe@hotmail.com"
  297. ]
  298. }
  299.  
  300.  
  301. prevent duplicates and add multiple values
  302. -------------------------------------------
  303.  
  304. db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")}, {"$addToSet" :
  305. ... {"emails" : {"$each" :
  306. ... ["joe@php.net", "joe@example.com", "joe@python.org"]}}})
  307.  
  308.  
  309. output
  310. ------
  311.  
  312. {
  313. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  314. "username" : "joe",
  315. "emails" : [
  316. "joe@example.com",
  317. "joe@gmail.com",
  318. "joe@yahoo.com",
  319. "joe@hotmail.com"
  320. "joe@php.net"
  321. "joe@python.org"]
  322. }
  323.  
  324.  
  325.  
  326. Removing Elements
  327. ------------------
  328.  
  329. db.lists.insert({"todo" : ["dishes", "laundry", "dry cleaning"]})
  330.  
  331. db.lists.update({}, {"$pull" : {"todo" : "laundry"}})
  332.  
  333. output
  334. ------
  335.  
  336. db.lists.find()
  337. {
  338. "_id" : ObjectId("4b2d75476cc613d5ee930164"),
  339. "todo" : [
  340. "dishes",
  341. "dry cleaning"
  342. ]
  343. }
  344.  
  345.  
  346. Note : $pull will remove all matching elements for example [1, 1, 2, 1] if pull 1 means remaining is 2 only.
  347.  
  348.  
  349. distinct
  350. --------
  351.  
  352. { "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
  353. { "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
  354. { "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
  355. { "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
  356.  
  357.  
  358. db.inventory.distinct( "dept" )
  359.  
  360.  
  361. output
  362. ------
  363.  
  364. { "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
  365. { "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
  366.  
  367.  
  368.  
  369. Positional array modifiers
  370. --------------------------
  371.  
  372. ...
  373. "comments" : [
  374. {
  375. "comment" : "good post",
  376. "author" : "John",
  377. "votes" : 0
  378. },
  379. {
  380. "comment" : "i thought it was too short",
  381. "author" : "Claire",
  382. "votes" : 3
  383. },
  384. {
  385. "comment" : "free watches",
  386. "author" : "Alice",
  387. "votes" : -1
  388. }
  389. ]
  390.  
  391.  
  392. If we want to increment the number of votes for the first comment, we can say the
  393. following:
  394. > db.blog.update({"post" : post_id},
  395. ... {"$inc" : {"comments.0.votes" : 1}})
  396.  
  397.  
  398. if we dont know the index use $ operator
  399.  
  400.  
  401. db.blog.update({"comments.author" : "John"},
  402. ... {"$set" : {"comments.$.author" : "Jim"}})
  403.  
  404.  
  405.  
  406. findAndModify Example
  407. ---------------------
  408.  
  409. ps = db.runCommand({"findAndModify" : "processes",
  410. ... "query" : {"status" : "READY"},
  411. ... "sort" : {"priority" : -1},
  412. ... "update" : {"$set" : {"status" : "RUNNING"}})
  413.  
  414. we can also remove a field using this,
  415.  
  416. db.runCommand({"findAndModify" : "processes",
  417. "query" : {"status" : "READY"},
  418. "sort" : {"priority" : -1},
  419. "remove" : true}).value
  420.  
  421.  
  422.  
  423. specifies keys to return in find
  424. ---------------------------------
  425.  
  426. db.users.find({}, {"username" : 1, "email" : 1})
  427.  
  428.  
  429. prevent id from beign return
  430. -----------------------------
  431.  
  432. db.users.find({}, {"username" : 1, "_id" : 0})
  433.  
  434.  
  435. conditonal querying example
  436. ---------------------------
  437.  
  438. db.users.find({}, {"username" : 1, "_id" : 0})
  439.  
  440.  
  441. > start = new Date("01/01/2007")
  442. > db.users.find({"registered" : {"$lt" : start}})
  443.  
  444. db.raffle.find({"ticket_no" : {"$in" : [725, 542, 390]}})
  445.  
  446. db.raffle.find({"ticket_no" : {"$nin" : [725, 542, 390]}})
  447.  
  448. db.raffle.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]})
  449.  
  450.  
  451. $or can contain nested conditions
  452.  
  453. db.raffle.find({"$or" : [{"ticket_no" : {"$in" : [725, 542, 390]}},
  454. {"winner" : true}]})
  455.  
  456. db.users.find({"id_num" : {"$mod" : [5, 1]}})
  457.  
  458. db.users.find({"id_num" : {"$not" : {"$mod" : [5, 1]}}})
  459.  
  460.  
  461. type specific queries
  462. ---------------------
  463.  
  464. db.c.find({"y" : null})
  465.  
  466.  
  467. Regular Expressions
  468. --------------------
  469.  
  470. db.users.find({"name" : /joey?/i})
  471.  
  472.  
  473. Querying Arrays
  474. ---------------
  475.  
  476. db.food.insert({"fruit" : ["apple", "banana", "peach"]})
  477.  
  478. db.food.find({"fruit" : "banana"})
  479.  
  480.  
  481. find all rows contain both using $all
  482. -------------------------------------
  483.  
  484. db.food.find({fruit : {$all : ["apple", "banana"]}})
  485.  
  486.  
  487. query value with given size $size
  488. ---------------------------------
  489.  
  490. db.food.find({"fruit" : {"$size" : 3}})
  491.  
  492.  
  493.  
  494. $slice
  495. ------
  496.  
  497. db.blog.posts.findOne(criteria, {"comments" : {"$slice" : 10}})
  498.  
  499. we can use below for last ten comments
  500.  
  501. db.blog.posts.findOne(criteria, {"comments" : {"$slice" : -10}})
  502.  
  503.  
  504. following will be very useful for pagination
  505.  
  506. db.blog.posts.findOne(criteria, {"comments" : {"$slice" : [23, 10]}})
  507.  
  508.  
  509. Querying on Embedded docs
  510. -------------------------
  511.  
  512. db.people.find({"name.first" : "Joe", "name.last" : "Schmoe"})
  513.  
  514.  
  515. sort using sot()
  516. ----------------
  517.  
  518. db.c.find().sort({username : 1, age : -1})
  519.  
  520.  
  521.  
  522. index
  523. -----
  524.  
  525. db.users.ensureIndex({"username" : 1})
  526.  
  527.  
  528. compund index
  529. -------------
  530.  
  531. db.users.find().sort({"age" : 1, "username" : 1})
  532.  
  533.  
  534. indexing object
  535. --------------
  536.  
  537. db.users.ensureIndex({"loc.city" : 1})
  538.  
  539. indexing specific Array
  540. -----------------------
  541.  
  542. db.blog.ensureIndex({"comments.10.votes": 1})
  543.  
  544.  
  545. unique index
  546. ------------
  547.  
  548. db.users.ensureIndex({"username" : 1}, {"unique" : true})
  549.  
  550.  
  551. removing or dropping duplicates names by index
  552. ----------------------------------------------
  553.  
  554. db.people.ensureIndex({"username" : 1}, {"unique" : true, "dropDups" : true})
  555.  
  556.  
  557. select not in list
  558. ------------------
  559.  
  560. db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
  561.  
  562. 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.
  563.  
  564.  
  565. $nor
  566. ---
  567.  
  568. db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ] } )
  569.  
  570. This query will return all documents that:
  571.  
  572. 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
  573. contain the price field whose value is not equal to 1.99 but do not contain the sale field or
  574. do not contain the price field but contain the sale field whose value is not equal to true or
  575. do not contain the price field and do not contain the sale field
  576. $nor and Additional Comparisons
  577.  
  578.  
  579. $exists
  580. -------
  581.  
  582. db.inventory.find( { qty: { $exists: true, $nin: [ 5, 15 ] } } )
  583.  
  584. This query will select all documents in the inventory collection where the qty field exists and its value does not equal 5 or 15.
  585.  
  586.  
  587. $type
  588. -----
  589.  
  590. db.grades.insertMany(
  591. [
  592. { "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 },
  593. { "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" },
  594. { "_id" : 3, name : "Cathy Hart", classAverage: "94.06" },
  595. { "_id" : 4, name : "Drew Williams" , classAverage : 93 }
  596. ]
  597. )
  598.  
  599.  
  600. db.grades.find( { "classAverage" : { $type : [ "string" , "double" ] } } );
  601.  
  602. output
  603. ------
  604. { "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 }
  605. { "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" }
  606. { "_id" : 3, name : "Cathy Hart", classAverage: "94.06" }
  607.  
  608.  
  609.  
  610. Application design
  611. ------------------
  612.  
  613. Two kinds of design
  614.  
  615. 1 Embedding
  616. best for small documents
  617. best for data changing less often
  618. best for where need fast reads
  619. 2 Reference
  620. best for large documents
  621. best for where need fast writes
Add Comment
Please, Sign In to add comment