|
| 1 | +require 'bundler/inline' |
| 2 | + |
| 3 | +gemfile do |
| 4 | + source 'https://rubygems.org' |
| 5 | + gem 'mongo' |
| 6 | +end |
| 7 | + |
| 8 | +uri = '<connection string>' |
| 9 | + |
| 10 | +Mongo::Client.new(uri) do |client| |
| 11 | + # start-setup |
| 12 | + database = client.use('db') |
| 13 | + collection = database[:fruits] |
| 14 | + |
| 15 | + # Inserts documents representing fruits |
| 16 | + fruits = [ |
| 17 | + { _id: 1, name: 'apples', qty: 5, rating: 3, color: 'red', type: ['fuji', 'honeycrisp'] }, |
| 18 | + { _id: 2, name: 'bananas', qty: 7, rating: 4, color: 'yellow', type: ['cavendish'] }, |
| 19 | + { _id: 3, name: 'oranges', qty: 6, rating: 2, type: ['naval', 'mandarin'] }, |
| 20 | + { _id: 4, name: 'pineapples', qty: 3, rating: 5, color: 'yellow' } |
| 21 | + ] |
| 22 | + |
| 23 | + collection.insert_many(fruits) |
| 24 | + # end-setup |
| 25 | + |
| 26 | + # Retrieves documents in which the "color" value is "yellow" |
| 27 | + # start-find-exact |
| 28 | + filter = { color: 'yellow' } |
| 29 | + results = collection.find(filter) |
| 30 | + results.each do |doc| |
| 31 | + puts doc |
| 32 | + end |
| 33 | + # end-find-exact |
| 34 | + |
| 35 | + # Retrieves and prints documents in which the "rating" value is greater than 2 |
| 36 | + # start-find-comparison |
| 37 | + filter = { rating: { '$gt' => 2 } } |
| 38 | + results = collection.find(filter) |
| 39 | + results.each do |doc| |
| 40 | + puts doc |
| 41 | + end |
| 42 | + # end-find-comparison |
| 43 | + |
| 44 | + # Retrieves and prints documents that match one or both query filters |
| 45 | + # start-find-logical |
| 46 | + filter = { '$or' => [{ qty: { '$gt' => 5 } }, { color: 'yellow' }] } |
| 47 | + results = collection.find(filter) |
| 48 | + results.each do |doc| |
| 49 | + puts doc |
| 50 | + end |
| 51 | + # end-find-logical |
| 52 | + |
| 53 | + # Retrieves and prints documents in which the "type" array has 2 elements |
| 54 | + # start-find-array |
| 55 | + filter = { type: { '$size' => 2 } } |
| 56 | + results = collection.find(filter) |
| 57 | + results.each do |doc| |
| 58 | + puts doc |
| 59 | + end |
| 60 | + # end-find-array |
| 61 | + |
| 62 | + # Retrieves and prints documents that have a "color" field |
| 63 | + # start-find-element |
| 64 | + filter = { color: { '$exists' => true } } |
| 65 | + results = collection.find(filter) |
| 66 | + results.each do |doc| |
| 67 | + puts doc |
| 68 | + end |
| 69 | + # end-find-element |
| 70 | + |
| 71 | + # Retrieves and prints documents in which the "name" value has at least two consecutive "p" characters |
| 72 | + # start-find-evaluation |
| 73 | + filter = { name: /p{2,}/ } |
| 74 | + results = collection.find(filter) |
| 75 | + results.each do |doc| |
| 76 | + puts doc |
| 77 | + end |
| 78 | + # end-find-evaluation |
| 79 | +end |
0 commit comments