├── ruby ├── mongoid │ ├── Gemfile │ ├── mongoid.yml │ └── mongoid_simple_example.rb └── ruby-driver │ └── ruby_simple_example.rb ├── README.md ├── php └── php_simple_example.php ├── python ├── pymongo_simple_example.py └── pymongo_production_connection_example.py ├── nodejs ├── mongooseSimpleExample.js └── nodeSimpleExample.js ├── c# └── CSharpSimpleExample.cs └── java └── JavaSimpleExample.java /ruby/mongoid/Gemfile: -------------------------------------------------------------------------------- 1 | source 'http://rubygems.org' 2 | 3 | gem 'mongoid', '6.1.0' -------------------------------------------------------------------------------- /ruby/mongoid/mongoid.yml: -------------------------------------------------------------------------------- 1 | production: 2 | clients: 3 | default: 4 | uri: "mongodb://user:pass@host:port/db" -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MongoDB Driver Examples 2 | 3 | This git repository includes mongodb connection and query examples 4 | for the following: 5 | 6 | - C# http://docs.mongodb.org/ecosystem/drivers/csharp/ 7 | 8 | - Java http://docs.mongodb.org/ecosystem/drivers/java/ 9 | 10 | - Node.js https://mongodb.github.io/node-mongodb-native/ 11 | 12 | - Node.js (Mongoose) http://mongoosejs.com/ 13 | 14 | - PHP http://docs.mongodb.org/ecosystem/drivers/php/ 15 | 16 | - Python (using pymongo) http://docs.mongodb.org/ecosystem/drivers/python/ 17 | 18 | - Ruby https://docs.mongodb.com/ruby-driver/master/ 19 | 20 | - Ruby (Mongoid) https://docs.mongodb.com/ruby-driver/master/mongoid/ 21 | 22 | 23 | These examples should run outright after you install the appropriate 24 | drivers and insert your MongoDB URI. See 25 | https://docs.mongodb.com/manual/installation/ for guidance. 26 | 27 | We hope these are helpful and appreciate your feedback! 28 | 29 | Sincerely, 30 | 31 | The mLab Team 32 | 33 | [mlab.com](http://www.mlab.com) | [@mLab](https://twitter.com/mlab) 34 | -------------------------------------------------------------------------------- /ruby/mongoid/mongoid_simple_example.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/ruby 2 | 3 | # Copyright (c) 2017 ObjectLabs Corporation 4 | # Distributed under the MIT license - http://opensource.org/licenses/MIT 5 | 6 | # Written with mongoid 6.1.0 7 | # Documentation: https://docs.mongodb.com/ruby-driver/master/mongoid/ 8 | # A mongoid script connecting to a MongoDB database given a MongoDB Connection URI. 9 | 10 | require 'mongoid' 11 | Mongoid.load!('mongoid.yml', :production) 12 | 13 | ### Define Schema 14 | 15 | class Song 16 | include Mongoid::Document 17 | field :decade 18 | field :artist 19 | field :song 20 | field :weeksAtOne 21 | store_in collection: 'songs' 22 | end 23 | 24 | ### Create seed data 25 | 26 | seventies = Song.new( 27 | decade: '1970s', 28 | artist: 'Debby Boone', 29 | song: 'You Light Up My Life', 30 | weeksAtOne: 10 31 | ) 32 | 33 | eighties = Song.new( 34 | decade: '1980s', 35 | artist: 'Olivia Newton-John', 36 | song: 'Physical', 37 | weeksAtOne: 10 38 | ) 39 | 40 | nineties = Song.new( 41 | decade: '1990s', 42 | artist: 'Mariah Carey', 43 | song: 'One Sweet Day', 44 | weeksAtOne: 16 45 | ) 46 | 47 | ### Write the songs to your MongoDB 48 | 49 | seventies.save! 50 | eighties.save! 51 | nineties.save! 52 | 53 | # We need to give Boyz II Men credit for their contribution to 54 | # the hit "One Sweet Day" 55 | 56 | Song.where(song: 'One Sweet Day').update(artist: 'Mariah Carey ft. Boyz II Men') 57 | 58 | # Finally we run a query which returns all the hits that spent 10 or 59 | # more weeks at number 1 60 | 61 | songs = Song.where(:weeksAtOne.gte => 10).sort(decade: 1) 62 | 63 | songs.each{ |doc| puts "In the #{ doc['decade'] }," + 64 | " #{ doc['song'] } by #{ doc['artist'] }" + 65 | " topped the charts for #{ doc['weeksAtOne'] }" + 66 | " straight weeks." } 67 | 68 | ### Since this is an example, we"ll clean up after ourselves. 69 | 70 | Song.collection.drop() -------------------------------------------------------------------------------- /ruby/ruby-driver/ruby_simple_example.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/ruby 2 | 3 | # Copyright (c) 2017 ObjectLabs Corporation 4 | # Distributed under the MIT license - http://opensource.org/licenses/MIT 5 | 6 | # Written with mongo 2.4.1 7 | # Documentation: http://docs.mongodb.org/ecosystem/drivers/ruby/ 8 | # A ruby script connecting to a MongoDB database given a MongoDB Connection URI. 9 | 10 | require 'mongo' 11 | 12 | ### Create seed data 13 | 14 | seed_data = [ 15 | { 16 | decade: '1970s', 17 | artist: 'Debby Boone', 18 | song: 'You Light Up My Life', 19 | weeksAtOne: 10 20 | }, 21 | { 22 | decade: '1980s', 23 | artist: 'Olivia Newton-John', 24 | song: 'Physical', 25 | weeksAtOne: 10 26 | }, 27 | { 28 | decade: '1990s', 29 | artist: 'Mariah Carey', 30 | song: 'One Sweet Day', 31 | weeksAtOne: 16 32 | } 33 | ] 34 | 35 | ### Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname 36 | 37 | uri = "mongodb://user:pass@host:port/db" 38 | 39 | client = Mongo::Client.new(uri) 40 | 41 | # First we'll add a few songs. Nothing is required to create the songs 42 | # collection; it is created automatically when we insert. 43 | 44 | songs = client[:songs] 45 | 46 | # Note that the insert_one method can take a single dict. Use insert_many to insert an array. 47 | 48 | songs.insert_many(seed_data) 49 | 50 | # Then we need to give Boyz II Men credit for their contribution to 51 | # the hit "One Sweet Day" 52 | 53 | query = { song: 'One Sweet Day' } 54 | 55 | songs.update_one(query, { '$set' => { artist: 'Mariah Carey ft. Boyz II Men' } }) 56 | 57 | # Finally we run a query which returns all the hits that spent 10 or 58 | # more weeks at number 1 59 | 60 | cursor = songs.find({ weeksAtOne: { '$gte' => 10 } }).sort({decade: 1}) 61 | 62 | cursor.each{ |doc| puts "In the #{ doc['decade'] }," + 63 | " #{ doc['song'] } by #{ doc['artist'] }" + 64 | " topped the charts for #{ doc['weeksAtOne'] }" + 65 | " straight weeks." } 66 | 67 | ### Since this is an example, we"ll clean up after ourselves. 68 | 69 | songs.drop() 70 | 71 | ### Only close the connection when your app is terminating 72 | 73 | client.close() -------------------------------------------------------------------------------- /php/php_simple_example.php: -------------------------------------------------------------------------------- 1 | '1970s', 18 | 'artist' => 'Debby Boone', 19 | 'song' => 'You Light Up My Life', 20 | 'weeksAtOne' => 10 21 | ), 22 | array( 23 | 'decade' => '1980s', 24 | 'artist' => 'Olivia Newton-John', 25 | 'song' => 'Physical', 26 | 'weeksAtOne' => 10 27 | ), 28 | array( 29 | 'decade' => '1990s', 30 | 'artist' => 'Mariah Carey', 31 | 'song' => 'One Sweet Day', 32 | 'weeksAtOne' => 16 33 | ), 34 | ); 35 | 36 | /* 37 | * Standard single-node URI format: 38 | * mongodb://[username:password@]host:port/[database] 39 | */ 40 | $uri = "mongodb://user:pass@host:port/db"; 41 | 42 | $client = new MongoDB\Client($uri); 43 | 44 | /* 45 | * First we'll add a few songs. Nothing is required to create the songs 46 | * collection; it is created automatically when we insert. 47 | */ 48 | $songs = $client->db->songs; 49 | 50 | // To insert a dict, use the insert method. 51 | $songs->insertMany($seedData); 52 | 53 | /* 54 | * Then we need to give Boyz II Men credit for their contribution to 55 | * the hit "One Sweet Day". 56 | */ 57 | $songs->updateOne( 58 | array('artist' => 'Mariah Carey'), 59 | array('$set' => array('artist' => 'Mariah Carey ft. Boyz II Men')) 60 | ); 61 | 62 | /* 63 | * Finally we run a query which returns all the hits that spent 10 64 | * or more weeks at number 1. 65 | */ 66 | $query = array('weeksAtOne' => array('$gte' => 10)); 67 | $options = array( 68 | "sort" => array('decade' => 1), 69 | ); 70 | $cursor = $songs->find($query,$options); 71 | 72 | foreach($cursor as $doc) { 73 | echo 'In the ' .$doc['decade']; 74 | echo ', ' .$doc['song']; 75 | echo ' by ' .$doc['artist']; 76 | echo ' topped the charts for ' .$doc['weeksAtOne']; 77 | echo ' straight weeks.', "\n"; 78 | } 79 | 80 | // Since this is an example, we'll clean up after ourselves. 81 | $songs->drop(); 82 | 83 | ?> -------------------------------------------------------------------------------- /python/pymongo_simple_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Copyright (c) 2017 ObjectLabs Corporation 4 | # Distributed under the MIT license - http://opensource.org/licenses/MIT 5 | 6 | __author__ = 'mLab' 7 | 8 | # Written with pymongo-3.4 9 | # Documentation: http://docs.mongodb.org/ecosystem/drivers/python/ 10 | # A python script connecting to a MongoDB given a MongoDB Connection URI. 11 | 12 | import sys 13 | import pymongo 14 | 15 | ### Create seed data 16 | 17 | SEED_DATA = [ 18 | { 19 | 'decade': '1970s', 20 | 'artist': 'Debby Boone', 21 | 'song': 'You Light Up My Life', 22 | 'weeksAtOne': 10 23 | }, 24 | { 25 | 'decade': '1980s', 26 | 'artist': 'Olivia Newton-John', 27 | 'song': 'Physical', 28 | 'weeksAtOne': 10 29 | }, 30 | { 31 | 'decade': '1990s', 32 | 'artist': 'Mariah Carey', 33 | 'song': 'One Sweet Day', 34 | 'weeksAtOne': 16 35 | } 36 | ] 37 | 38 | ### Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname 39 | 40 | uri = 'mongodb://user:pass@host:port/db' 41 | 42 | ############################################################################### 43 | # main 44 | ############################################################################### 45 | 46 | def main(args): 47 | 48 | client = pymongo.MongoClient(uri) 49 | 50 | db = client.get_default_database() 51 | 52 | # First we'll add a few songs. Nothing is required to create the songs 53 | # collection; it is created automatically when we insert. 54 | 55 | songs = db['songs'] 56 | 57 | # Note that the insert method can take either an array or a single dict. 58 | 59 | songs.insert_many(SEED_DATA) 60 | 61 | # Then we need to give Boyz II Men credit for their contribution to 62 | # the hit "One Sweet Day". 63 | 64 | query = {'song': 'One Sweet Day'} 65 | 66 | songs.update(query, {'$set': {'artist': 'Mariah Carey ft. Boyz II Men'}}) 67 | 68 | # Finally we run a query which returns all the hits that spent 10 or 69 | # more weeks at number 1. 70 | 71 | cursor = songs.find({'weeksAtOne': {'$gte': 10}}).sort('decade', 1) 72 | 73 | for doc in cursor: 74 | print ('In the %s, %s by %s topped the charts for %d straight weeks.' % 75 | (doc['decade'], doc['song'], doc['artist'], doc['weeksAtOne'])) 76 | 77 | ### Since this is an example, we'll clean up after ourselves. 78 | 79 | db.drop_collection('songs') 80 | 81 | ### Only close the connection when your app is terminating 82 | 83 | client.close() 84 | 85 | 86 | if __name__ == '__main__': 87 | main(sys.argv[1:]) -------------------------------------------------------------------------------- /python/pymongo_production_connection_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Copyright (c) 2017 ObjectLabs Corporation 4 | # Distributed under the MIT license - http://opensource.org/licenses/MIT 5 | 6 | from pymongo import MongoClient # pymongo>=3.2 7 | 8 | """ 9 | PyMongo Production Connection Example 10 | 11 | The following example uses PyMongo to connect to a MongoDB deployment using the options we have found most appropriate to 12 | production applications. This example supports both replica set and SSL connections. 13 | 14 | For demonstration purposes, configuration is hard-coded; in practice, configuration should be externalized e.g. into a file or 15 | environment variables. 16 | 17 | ########################################################################################################################## 18 | WARNING: This example requires PyMongo 3.2 or later to work correctly. In particular, if you are connecting over SSL 19 | with an earlier driver version additional configuration will be required for it to properly authenticate the 20 | server. 21 | ########################################################################################################################## 22 | """ 23 | 24 | # Your deployment's URI in the standard format (http://docs.mongodb.org/manual/reference/connection-string/). 25 | # 26 | # The URI can be found via the mLab management portal (http://docs.mlab.com/connecting/#connect-string). 27 | # 28 | # If you are using a PaaS add-on integration e.g. via Heroku, the URI is usually available via an environment variable. 29 | # Consult the documentation for the PaaS that you are using for more information on this. 30 | # uri = "mongodb://:@:,:/?replicaSet=&ssl=true" 31 | 32 | # Pass the following keyword arguments to ensure proper production behavior: 33 | # 34 | # connectTimeoutMS 30 s to allow for PaaS warm-up; adjust down as needed for faster failures. For more, see docs: 35 | # http://docs.mlab.com/timeouts/#connection-timeout 36 | # 37 | # socketTimeoutMS No timeout (None) to allow for long-running operations 38 | # (http://docs.mlab.com/timeouts/#socket-timeout). 39 | # 40 | # socketKeepAlive Enabled (True) to ensure idle connections are kept alive in the presence of a firewall. 41 | # 42 | # See PyMongo docs for more details about the connection options: 43 | # 44 | # https://api.mongodb.org/python/3.4.0/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient 45 | # 46 | client = MongoClient(uri, 47 | connectTimeoutMS=30000, 48 | socketTimeoutMS=None, 49 | socketKeepAlive=True) 50 | 51 | db = client.get_default_database() 52 | print db.collection_names() -------------------------------------------------------------------------------- /nodejs/mongooseSimpleExample.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 ObjectLabs Corporation 3 | * Distributed under the MIT license - http://opensource.org/licenses/MIT 4 | * 5 | * Written with: mongoose@5.0.3 6 | * Documentation: http://mongoosejs.com/docs/index.html 7 | * A Mongoose script connecting to a MongoDB database given a MongoDB Connection URI. 8 | */ 9 | const mongoose = require('mongoose'); 10 | 11 | let uri = 'mongodb://user:pass@host:port/dbname'; 12 | 13 | mongoose.connect(uri); 14 | 15 | let db = mongoose.connection; 16 | 17 | db.on('error', console.error.bind(console, 'connection error:')); 18 | 19 | db.once('open', function callback() { 20 | 21 | // Create song schema 22 | let songSchema = mongoose.Schema({ 23 | decade: String, 24 | artist: String, 25 | song: String, 26 | weeksAtOne: Number 27 | }); 28 | 29 | // Store song documents in a collection called "songs" 30 | let Song = mongoose.model('songs', songSchema); 31 | 32 | // Create seed data 33 | let seventies = new Song({ 34 | decade: '1970s', 35 | artist: 'Debby Boone', 36 | song: 'You Light Up My Life', 37 | weeksAtOne: 10 38 | }); 39 | 40 | let eighties = new Song({ 41 | decade: '1980s', 42 | artist: 'Olivia Newton-John', 43 | song: 'Physical', 44 | weeksAtOne: 10 45 | }); 46 | 47 | let nineties = new Song({ 48 | decade: '1990s', 49 | artist: 'Mariah Carey', 50 | song: 'One Sweet Day', 51 | weeksAtOne: 16 52 | }); 53 | 54 | /* 55 | * First we'll add a few songs. Nothing is required to create the 56 | * songs collection; it is created automatically when we insert. 57 | */ 58 | 59 | let list = [seventies, eighties, nineties] 60 | 61 | Song.insertMany(list).then(() => { 62 | 63 | /* 64 | * Then we need to give Boyz II Men credit for their contribution 65 | * to the hit "One Sweet Day". 66 | */ 67 | 68 | return Song.update({ song: 'One Sweet Day'}, { $set: { artist: 'Mariah Carey ft. Boyz II Men'} }) 69 | 70 | }).then(() => { 71 | 72 | /* 73 | * Finally we run a query which returns all the hits that spend 10 or 74 | * more weeks at number 1. 75 | */ 76 | 77 | return Song.find({ weeksAtOne: { $gte: 10} }).sort({ decade: 1}) 78 | 79 | }).then(docs => { 80 | 81 | docs.forEach(doc => { 82 | console.log( 83 | 'In the ' + doc['decade'] + ', ' + doc['song'] + ' by ' + doc['artist'] + 84 | ' topped the charts for ' + doc['weeksAtOne'] + ' straight weeks.' 85 | ); 86 | }); 87 | 88 | }).then(() => { 89 | 90 | // Since this is an example, we'll clean up after ourselves. 91 | return mongoose.connection.db.collection('songs').drop() 92 | 93 | }).then(() => { 94 | 95 | // Only close the connection when your app is terminating 96 | return mongoose.connection.close() 97 | 98 | }).catch(err => { 99 | 100 | // Log any errors that are thrown in the Promise chain 101 | console.log(err) 102 | 103 | }) 104 | }); 105 | -------------------------------------------------------------------------------- /nodejs/nodeSimpleExample.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 ObjectLabs Corporation 3 | * Distributed under the MIT license - http://opensource.org/licenses/MIT 4 | * 5 | * Written with: mongodb@3.0.2 6 | * Documentation: https://mongodb.github.io/node-mongodb-native/ 7 | * A Node script connecting to a MongoDB database given a MongoDB Connection URI. 8 | */ 9 | 10 | const mongodb = require('mongodb'); 11 | 12 | // Create seed data 13 | 14 | let seedData = [ 15 | { 16 | decade: '1970s', 17 | artist: 'Debby Boone', 18 | song: 'You Light Up My Life', 19 | weeksAtOne: 10 20 | }, 21 | { 22 | decade: '1980s', 23 | artist: 'Olivia Newton-John', 24 | song: 'Physical', 25 | weeksAtOne: 10 26 | }, 27 | { 28 | decade: '1990s', 29 | artist: 'Mariah Carey', 30 | song: 'One Sweet Day', 31 | weeksAtOne: 16 32 | } 33 | ]; 34 | 35 | // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname 36 | 37 | let uri = 'mongodb://user:pass@host:port/dbname'; 38 | 39 | mongodb.MongoClient.connect(uri, function(err, client) { 40 | 41 | if(err) throw err; 42 | 43 | /* 44 | * Get the database from the client. Nothing is required to create a 45 | * new database, it is created automatically when we insert. 46 | */ 47 | 48 | let db = client.db('dbname') 49 | 50 | /* 51 | * First we'll add a few songs. Nothing is required to create the 52 | * songs collection; it is created automatically when we insert. 53 | */ 54 | 55 | let songs = db.collection('songs'); 56 | 57 | // Note that the insert method can take either an array or a dict. 58 | 59 | songs.insert(seedData, function(err, result) { 60 | 61 | if(err) throw err; 62 | 63 | /* 64 | * Then we need to give Boyz II Men credit for their contribution 65 | * to the hit "One Sweet Day". 66 | */ 67 | 68 | songs.update( 69 | { song: 'One Sweet Day' }, 70 | { $set: { artist: 'Mariah Carey ft. Boyz II Men' } }, 71 | function (err, result) { 72 | 73 | if(err) throw err; 74 | 75 | /* 76 | * Finally we run a query which returns all the hits that spend 10 or 77 | * more weeks at number 1. 78 | */ 79 | 80 | songs.find({ weeksAtOne : { $gte: 10 } }).sort({ decade: 1 }).toArray(function (err, docs) { 81 | 82 | if(err) throw err; 83 | 84 | docs.forEach(function (doc) { 85 | console.log( 86 | 'In the ' + doc['decade'] + ', ' + doc['song'] + ' by ' + doc['artist'] + 87 | ' topped the charts for ' + doc['weeksAtOne'] + ' straight weeks.' 88 | ); 89 | }); 90 | 91 | // Since this is an example, we'll clean up after ourselves. 92 | songs.drop(function (err) { 93 | if(err) throw err; 94 | 95 | // Only close the connection when your app is terminating. 96 | client.close(function (err) { 97 | if(err) throw err; 98 | }); 99 | }); 100 | }); 101 | } 102 | ); 103 | }); 104 | }); 105 | 106 | -------------------------------------------------------------------------------- /c#/CSharpSimpleExample.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 ObjectLabs Corporation 3 | * Distributed under the MIT license - http://opensource.org/licenses/MIT 4 | * 5 | * Written with CSharpDriver-2.3.0 6 | * Documentation: http://docs.mongodb.org/ecosystem/drivers/csharp/ 7 | * A C# class connecting to a MongoDB database given a MongoDB Connection URI. 8 | */ 9 | 10 | using System; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | using MongoDB.Bson; 14 | using MongoDB.Driver; 15 | using MongoDB.Driver.Core; 16 | 17 | namespace SimpleExample 18 | { 19 | 20 | class Simple 21 | { 22 | 23 | // Extra helper code 24 | static BsonDocument[] CreateSeedData() 25 | { 26 | BsonDocument seventies = new BsonDocument { 27 | { "Decade" , "1970s" }, 28 | { "Artist" , "Debby Boone" }, 29 | { "Title" , "You Light Up My Life" }, 30 | { "WeeksAtOne" , 10 } 31 | }; 32 | 33 | BsonDocument eighties = new BsonDocument { 34 | { "Decade" , "1980s" }, 35 | { "Artist" , "Olivia Newton-John" }, 36 | { "Title" , "Physical" }, 37 | { "WeeksAtOne" , 10 } 38 | }; 39 | 40 | BsonDocument nineties = new BsonDocument { 41 | { "Decade" , "1990s" }, 42 | { "Artist" , "Mariah Carey" }, 43 | { "Title" , "One Sweet Day" }, 44 | { "WeeksAtOne" , 16 } 45 | }; 46 | 47 | BsonDocument[] SeedData = { seventies, eighties, nineties }; 48 | return SeedData; 49 | } 50 | 51 | async static Task AsyncCrud(BsonDocument[] seedData) 52 | { 53 | // Create seed data 54 | BsonDocument[] songData = seedData; 55 | 56 | // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname 57 | String uri = "mongodb://user:pass@host:port/db"; 58 | 59 | var client = new MongoClient(uri); 60 | var db = client.GetDatabase("db"); 61 | 62 | /* 63 | * First we'll add a few songs. Nothing is required to create the 64 | * songs collection; it is created automatically when we insert. 65 | */ 66 | 67 | var songs = db.GetCollection("songs"); 68 | 69 | // Use InsertOneAsync for single BsonDocument insertion. 70 | await songs.InsertManyAsync(songData); 71 | 72 | /* 73 | * Then we need to give Boyz II Men credit for their contribution to 74 | * the hit "One Sweet Day". 75 | */ 76 | 77 | var updateFilter = Builders.Filter.Eq("Title", "One Sweet Day"); 78 | var update = Builders.Update.Set("Artist", "Mariah Carey ft. Boyz II Men"); 79 | 80 | await songs.UpdateOneAsync(updateFilter, update); 81 | 82 | /* 83 | * Finally we run a query which returns all the hits that spent 10 84 | * or more weeks at number 1. 85 | */ 86 | 87 | var filter = Builders.Filter.Gte("WeeksAtOne", 10); 88 | var sort = Builders.Sort.Ascending("Decade"); 89 | 90 | await songs.Find(filter).Sort(sort).ForEachAsync(song => 91 | Console.WriteLine("In the {0}, {1} by {2} topped the charts for {3} straight weeks", 92 | song["Decade"], song["Title"], song["Artist"], song["WeeksAtOne"]) 93 | ); 94 | 95 | // Since this is an example, we'll clean up after ourselves. 96 | await db.DropCollectionAsync("songs"); 97 | } 98 | 99 | static void Main() 100 | { 101 | BsonDocument[] seedData = CreateSeedData(); 102 | AsyncCrud(seedData).Wait(); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /java/JavaSimpleExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 ObjectLabs Corporation 3 | * Distributed under the MIT license - http://opensource.org/licenses/MIT 4 | * 5 | * Written with mongo-3.4.2.jar 6 | * Documentation: http://api.mongodb.org/java/ 7 | * A Java class connecting to a MongoDB database given a MongoDB Connection URI. 8 | */ 9 | import java.net.UnknownHostException; 10 | 11 | import com.mongodb.MongoClient; 12 | import com.mongodb.MongoClientURI; 13 | import com.mongodb.ServerAddress; 14 | 15 | import com.mongodb.client.MongoDatabase; 16 | import com.mongodb.client.MongoCollection; 17 | 18 | import org.bson.Document; 19 | import java.util.Arrays; 20 | import com.mongodb.Block; 21 | 22 | import com.mongodb.client.MongoCursor; 23 | import static com.mongodb.client.model.Filters.*; 24 | import com.mongodb.client.result.DeleteResult; 25 | import static com.mongodb.client.model.Updates.*; 26 | import com.mongodb.client.result.UpdateResult; 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | public class JavaSimpleExample { 31 | 32 | public static void main(String[] args) throws UnknownHostException{ 33 | 34 | // Create seed data 35 | 36 | List seedData = new ArrayList(); 37 | 38 | seedData.add(new Document("decade", "1970s") 39 | .append("artist", "Debby Boone") 40 | .append("song", "You Light Up My Life") 41 | .append("weeksAtOne", 10) 42 | ); 43 | 44 | seedData.add(new Document("decade", "1980s") 45 | .append("artist", "Olivia Newton-John") 46 | .append("song", "Physical") 47 | .append("weeksAtOne", 10) 48 | ); 49 | 50 | seedData.add(new Document("decade", "1990s") 51 | .append("artist", "Mariah Carey") 52 | .append("song", "One Sweet Day") 53 | .append("weeksAtOne", 16) 54 | ); 55 | 56 | // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname 57 | 58 | MongoClientURI uri = new MongoClientURI("mongodb://user:pass@host:port/db"); 59 | MongoClient client = new MongoClient(uri); 60 | MongoDatabase db = client.getDatabase(uri.getDatabase()); 61 | 62 | /* 63 | * First we'll add a few songs. Nothing is required to create the 64 | * songs collection; it is created automatically when we insert. 65 | */ 66 | 67 | MongoCollection songs = db.getCollection("songs"); 68 | 69 | // Note that the insert method can take either an array or a document. 70 | 71 | songs.insertMany(seedData); 72 | 73 | /* 74 | * Then we need to give Boyz II Men credit for their contribution to 75 | * the hit "One Sweet Day". 76 | */ 77 | 78 | Document updateQuery = new Document("song", "One Sweet Day"); 79 | songs.updateOne(updateQuery, new Document("$set", new Document("artist", "Mariah Carey ft. Boyz II Men"))); 80 | 81 | /* 82 | * Finally we run a query which returns all the hits that spent 10 83 | * or more weeks at number 1. 84 | */ 85 | 86 | Document findQuery = new Document("weeksAtOne", new Document("$gte",10)); 87 | Document orderBy = new Document("decade", 1); 88 | 89 | MongoCursor cursor = songs.find(findQuery).sort(orderBy).iterator(); 90 | 91 | try { 92 | while (cursor.hasNext()) { 93 | Document doc = cursor.next(); 94 | System.out.println( 95 | "In the " + doc.get("decade") + ", " + doc.get("song") + 96 | " by " + doc.get("artist") + " topped the charts for " + 97 | doc.get("weeksAtOne") + " straight weeks." 98 | ); 99 | } 100 | } finally { 101 | cursor.close(); 102 | } 103 | 104 | // Since this is an example, we'll clean up after ourselves. 105 | 106 | songs.drop(); 107 | 108 | // Only close the connection when your app is terminating 109 | 110 | client.close(); 111 | } 112 | } --------------------------------------------------------------------------------