Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.77 KB | None | 0 0
  1. #MongoDB - Basic Commands
  2.  
  3. ##Saving Data
  4.  
  5. db //Tells you the current database
  6.  
  7. show collections //Shows the collections available in the current db
  8.  
  9. db.foo.save({_id:1, x:10}) //Save the document into the foo collection
  10. db.bar.save({_id:1, x:10}) //Save the document into the bar collection
  11.  
  12. You can view the data using:
  13.  
  14. db.foo.find() //Normal
  15. db.foo.find.pretty() //Formats the data to make it more viewable
  16. db.foo.count() //Shows the number of documents in the collection
  17.  
  18. Mongo will automatically create a ```system.indexes``` collection with an index entry for both collections for the _id field.
  19.  
  20. ###_id field types
  21. The _id field can be a number of different types. For example maybe some data is better indexed as a date like log entries etc.
  22.  
  23. db.foo.save({ _id: 1 })
  24. db.foo.save({ _id: 3.14 })
  25. db.foo.save({ _id: "Hello" })
  26. db.foo.save({ _id: ISODate() })
  27. db.foo.save({ _id: { a:'X', b:2 } })
  28.  
  29. db.foo.find()
  30.  
  31. { "_id" : 1 }
  32. { "_id" : 2, "value" : "replication is cool" }
  33. { "_id" : 3.14 }
  34. { "_id" : "Hello" }
  35. { "_id" : ISODate("2013-09-29T11:29:06.038Z") }
  36. { "_id" : { "a" : "X", "b" : 2 } }
  37.  
  38. The only data type which cannot be used as an _id is an array. You can of course convert the array into a byte structure and use that instead.
  39.  
  40. ###Mongo ObjectId
  41.  
  42. If no _id is specified mongo will assign an ObjectId as the _id. You can see this using:
  43.  
  44. db.Users.save({name: 'John'})
  45. db.Users.find()
  46. { "_id" : ObjectId("5248106f6538d4e1cf6daefd"), "name" : "John" }
  47.  
  48. The ObjectId is an amalgamation of a timestamp and an incrementing index. You can generate a new ObjectId using:
  49.  
  50. ObjectId()
  51. ObjectId("524811b8d6f4a7be80e3b029")
  52.  
  53. ObjectId().getTimestamp()
  54. ISODate("2013-09-29T11:41:18Z")
  55.  
  56. In the example above, we can access the timestamp using:
  57.  
  58. db.Users.findOne({name: 'John'})._id.getTimestamp()
  59.  
  60.  
  61. ###Optimizing Read and Writes
  62. The ObjectId has the advantage of being sequential and therefore it is faster for writing as each record is just appended on to the end of the file. However, if you need
  63.  
  64. ###save v insert
  65. It is possible to save two documents with the same _id.
  66.  
  67.   db.foo.save({_id:1, x:10})
  68. db.foo.save({_id:1, name: "John"})
  69.  
  70. In this case the last entry is what is stored. So the record at _id: 1 will be pointing to {_id:1, name: "John"}. No error occurs when the second save is done.
  71.  
  72. There is another option, the update. In this case when the second entry is done it will report and error.
  73.  
  74.   db.a.insert({_id:1, x:10})
  75. db.a.insert({_id:1, name: "John"})
  76. E11000 duplicate key error index: test.foo.$_id_ dup key: { : 1.0 }
  77.  
  78. ##Updating Data
  79. The db.update allows for a sequential update of record data.
  80.  
  81. db.foo.update(query, update, options);
  82.  
  83. The options parameter is optional. Options include update one, update many or Upsert (ie update if it exists, insert if it doesn't).
  84.  
  85. db.a.save({_id:1, x:10})
  86. db.a.update({_id:1},{$inc:{x:1}})
  87. db.a.find()
  88. { "_id" : 1, "x" : 11}
  89.  
  90. ###Adding a field to a document
  91.  
  92. db.b.save({_id:1, x:10})
  93. db.b.update({_id:1},{$set:{y:9}})
  94.  
  95. ###Removing a field from a document
  96.  
  97. db.b.update({_id:1},{$unset:{y: ''}})
  98.  
  99. In this case the y value is arbitrary.
  100.  
  101. To remove the field from all fields you would use:
  102.  
  103. db.b.update({},{$unset:{y: ''}}, {multi: true})
  104.  
  105. In this case the options ```{multi: 1}``` tells mongo to apply it to multiple documents. The selector of ```{}``` tells it to select to all documents. You could tell it to only update certain documents based on a selection:
  106.  
  107. db.a.update({x: {$lt: 11}},{$unset:{y: ''}}, {multi: true})
  108.  
  109. This removes the field where the value of x is less than 11 for all documents that meet the criteria.
  110.  
  111. ###Renaming a field in a document
  112.  
  113. db.b.save({_id:1, naem: 'John'})
  114. db.b.find()
  115. { "_id" : 1, "naem" : "bob" }
  116. db.b.update({_id:1},{$rename:{ 'naem': 'name' }})
  117.  
  118. ###Adding a value to an array field
  119.  
  120. db.a.save({_id:1})
  121. db.a.find()
  122. { "_id" : 1 }
  123. db.a.update({_id:1}, {$push: {things: 'one' }})
  124. db.a.find()
  125. { "_id" : 1, "things" : [ "one" ] }
  126. db.a.update({_id:1}, {$push: {things: 'two' }})
  127.  
  128. ###Add a value to a set field
  129. A set is the same as an array but it cannot contain duplicates.
  130.  
  131. db.a.update({_id:1}, {$addToSet: {things: 'two' }})
  132.  
  133. ###Remove a value from an array
  134.  
  135. db.a.update({_id:1}, {$pull: {things: 'two' }})
  136.  
  137. ###Remove the last item from an array
  138.  
  139. db.a.update({_id:1}, {$pop: {things: 1 }})
  140.  
  141. The 1 in this case refers to the item 1 from the end.
  142.  
  143. ###Remove the first item from an array
  144.  
  145. db.a.update({_id:1}, {$pop: {things: -1 }})
  146.  
  147. The -1 in this case refers to the item 1 from the start.
  148.  
  149. ###Updating Multiple Records
  150. The default when doing an update is to only update one record. Therefore if you have 4 records like this:
  151.  
  152. db.a.find()
  153. { "_id" : 1, "things" : [ 1, 2, 3 ]}
  154. { "_id" : 2, "things" : [ 2, 3 ]}
  155. { "_id" : 3, "things" : [ 3 ]}
  156. { "_id" : 4, "things" : [ 1, 3 ]}
  157.  
  158. And we do an update:
  159.  
  160. db.a.update({}, {$push: {things: 4}});
  161.  
  162. Instead of adding to all the records like you would expect it gives us:
  163.  
  164. db.a.find()
  165. { "_id" : 1, "things" : [ 1, 2, 3, 4 ]}
  166. { "_id" : 2, "things" : [ 2, 3 ]}
  167. { "_id" : 3, "things" : [ 3 ]}
  168. { "_id" : 4, "things" : [ 1, 3 ]}
  169.  
  170. So, it only add to record 1. To update multiple rows you need to set {multi:true}.
  171.  
  172. db.a.update({}, {$push: {things: 4}}, {multi:true});
  173.  
  174. db.a.find()
  175. { "_id" : 1, "things" : [ 1, 2, 3, 4, 4 ]}
  176. { "_id" : 2, "things" : [ 2, 3, 4 ]}
  177. { "_id" : 3, "things" : [ 3, 4 ]}
  178. { "_id" : 4, "things" : [ 1, 3, 4 ]}
  179.  
  180. ###Updating Multiple Records based on Criteria
  181. If you want to update records which contain 2 you can do it with the following query:
  182.  
  183. db.a.update({things:2}, {$push: {things: 42}}, {multi:true});
  184.  
  185. db.a.find()
  186. { "_id" : 1, "things" : [ 1, 2, 3, 4, 4, 42 ]}
  187. { "_id" : 2, "things" : [ 2, 3, 4, 42 ]}
  188. { "_id" : 3, "things" : [ 3, 4 ]}
  189. { "_id" : 4, "things" : [ 1, 3, 4 ]}
  190.  
  191. ###Find and Modify
  192. Find and Modify will find and update one document which matches the query. Typically the query is something like ```{_id: 10}```.
  193.  
  194. db.foo.findAndModify({
  195. query: <document>,
  196. update: <document>,
  197. upsert: <document>,
  198. remove: <boolean>,
  199. new: <boolean>,
  200. sort: <document>,
  201. fields: <document> });
  202.  
  203. By default findAndModify will return a the record before the modification unless ```new``` is set to true. Then it will return the record after the modification. You can select the fields to return rather than the whole document. If remove is set to true then it will delete the document. ```upsert``` will tell it to create the document if it does not already exist. ```remove``` will delete the record. ```fields``` tells what fields you want returned from the command in case you do not want all the fields to be returned.
  204.  
  205. db.a.findAndModify({query: {x: {$gt: 18}}, update: {$inc:{x:2}}, new: true})
  206.  
  207. This will find and update only one document.
  208.  
  209. ###FindOne
  210. ```findOne``` returns only one document.
  211.  
  212. findOne({_id:1})
  213.  
  214.  
  215. ###Find
  216.  
  217. db.foo.find(query, projection)
  218.  
  219. The ```query``` part determines the selection criteria and the ```projection``` refers to the field that you wish to return. Please note that there is a speed cost of returning lots of unneeded fields so you should only return the smallest set of data necessary. If you do not specify a ```projection``` then all the fields are returned. Note that unlike findOne, find returns a cursor and does not point to the data directly. You can still carry out functions on the results of the cursor like sort, skip, limit etc.
  220.  
  221. db.a.find({_id: 1})
  222. //_id is always unique so this will return only one document
  223. //{ "_id" : 1, "x" : 28, "y" : 2 }
  224.  
  225. db.a.find({x: 28, y: 2})
  226. //returns all documents where x = 28 and y =2
  227. //{ "_id" : 1, "x" : 28, "y" : 2 }
  228.  
  229. ####Projections (Fields)
  230. By default mongo return all the fields in a document. You cna specify a projection if you wish to specify which fields to return. Note: it treats both ```true``` and ```1``` as ```true```, so a projection of ```db.a.find({_id: 1},{x: true, y: 1})``` will return both the x and y fields as well as the ```_id``` which is always returned. You can also tell it what fields not to return, so ```db.a.find({_id: 1},{_id: false})``` will return all the fields except the ```_id``` field. You can only include or exclude fields, you cannot use the projection to include and exclude fields in the same projection.
  231.  
  232. ####Ranges
  233. You can also specify ranges:
  234.  
  235. db.a.find({_id: {$gt:1, $lt:4}}, {_id:1}
  236.  
  237. In this the query returns where the ```_id``` is greater than 1 and less than 4. It also returns only the ```_id``` field.
  238.  
  239. You can also use the ```$in``` operator
  240.  
  241. db.a.find({_id: {$in: [1,3]}}, {_id:1})
  242.  
  243. This will return all documents where the ```_id``` is in the set [1,3] (ie 1 or 3)
  244.  
  245. You can also find all those not in the set using:
  246.  
  247. db.a.find({_id: {$nin: [1,3]}}, {_id:1})
  248.  
  249. ####Negation
  250.  
  251. You can also use negation (normally you would just use ```$lt``` here but it is just for example):
  252.  
  253. db.a.find({_id: {$not: {$gt:3}}}, {_id:1}
  254.  
  255. ####Arrays
  256. You can also find elements in an array:
  257.  
  258. db.animals.save({_id: 1, name: "cat", tags: ["cute", "land"], info: {type: 'carnivore'}})
  259. db.animals.save({_id: 2, name: "rabbit", tags: ["cute", "land"], info: {type: 'herbivore'}})
  260. db.animals.save({_id: 3, name: "shark", tags: ["ocean"], info: {type: 'carnivore', color: null}})
  261. db.animals.save({_id: 4, name: "dolphin", tags: ["cute", "ocean"], info: {type: 'carnivore', color: 'grey'}})
  262. db.animals.save({_id: 5, name: "rat", tags: ["land"], info: {type: 'omnivore'}})
  263.  
  264. To find any documents that have a tag or either 'ocean' or 'cute' use the ```$in``` operator:
  265.  
  266. db.animals.find({tags: {$in: ['cute', 'ocean']}}, {name: 1})
  267.  
  268. { "_id" : 1, "name" : "cat" }
  269. { "_id" : 2, "name" : "rabbit" }
  270. { "_id" : 3, "name" : "shark" }
  271. { "_id" : 4, "name" : "dolphin" }
  272.  
  273. To find documents that have tags of both 'cute' and 'ocean' use the ```$all``` operator:
  274.  
  275. db.animals.find({tags: {$all: ['cute', 'ocean']}}, {name: 1})
  276.  
  277. { "_id" : 4, "name" : "dolphin" }
  278.  
  279. To check for documents not in 'cute' or 'ocean' you can use ```$nin```.
  280.  
  281. db.animals.find({tags: {$nin: ['cute', 'ocean']}}, {name: 1})
  282.  
  283. { "_id" : 5, "name" : "rat" }
  284.  
  285. ####Dot Notation
  286. You can access field in a subdocument using dot notation as follows:
  287.  
  288. db.animals.find({'info.type': 'omnivore'})
  289. //Same as db.animals.find({info: {type: 'omnivore'}})
  290.  
  291. { "_id" : 5, "name" : "rat", "tags" : [ "land" ], "info" : { "type" : "omnivore" } }
  292.  
  293. Note that Mongo is loosely typed so there is no problem if the particular field does not exist on the document, it is just skipped if it is not there.
  294.  
  295. ####Null fields
  296. A field value can be null if either it is set to the value or ```null`` or it does not exist.
  297.  
  298. db.animals.find({'info.color': 'grey'}, {name: 1, info: 1})
  299.  
  300. { "_id" : 4, "name" : "dolphin", "info" : { "type" : "carnivore", "color" : "grey" } }
  301.  
  302. Searching for null gives us:
  303.  
  304. db.animals.find({'info.color': null}, {name: 1, info: 1})
  305.  
  306. { "_id" : 1, "name" : "cat", "info" : { "type" : "carnivore" } }
  307. { "_id" : 2, "name" : "rabbit", "info" : { "type" : "herbivore" } }
  308. { "_id" : 3, "name" : "shark", "info" : { "type" : "carnivore", "color" : null } }
  309. { "_id" : 5, "name" : "rat", "info" : { "type" : "omnivore" } }
  310.  
  311. This returns where the field is ```null``` ie for the shark and where the field does not exist at all.
  312.  
  313. ####Check for field existence
  314. To check if field exists you can use the ```$exists``` operator.
  315.  
  316. db.animals.find({'info.color': {$exists: true}}, {name: 1, info: 1})
  317.  
  318. { "_id" : 3, "name" : "shark", "info" : { "type" : "carnivore", "color" : null } }
  319. { "_id" : 4, "name" : "dolphin", "info" : { "type" : "carnivore", "color" : "grey" } }
  320.  
  321. This returns the documents which have the field, even if the value is null. the opposite of this is:
  322.  
  323. db.animals.find({'info.color': {$exists: false}}, {name: 1, info: 1})
  324.  
  325. { "_id" : 1, "name" : "cat", "info" : { "type" : "carnivore" } }
  326. { "_id" : 2, "name" : "rabbit", "info" : { "type" : "herbivore" } }
  327. { "_id" : 5, "name" : "rat", "info" : { "type" : "omnivore" } }
  328.  
  329. Note: the existence of a field can be a useful indicator of the version of the document. So v1 of the api has one field, v2 of the api has a different field etc.
  330.  
  331. ###Sorting
  332. You can sort the results (1 is ascending, -1 is descending) of a find using:
  333.  
  334. db.animals.find({}, {name: 1}).sort({name: 1})
  335.  
  336. You can also sort on multiple fields using:
  337.  
  338. db.animals.find({}, {name: 1}).sort({name: 1, 'info.type': 1})
  339.  
  340. ###Limit
  341. You can limit the number of documents returned. This can be useful for paging or finding the top 10 results etc.
  342.  
  343. db.animals.find({}).limit(2)
  344.  
  345. ###Skip
  346. Skip is useful for paging.
  347.  
  348. db.animals.find({}).skip(2).limit(2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement