2015-11-04 10:10:20.0|分类: MongoDB|浏览量: 1231
MongoDB Driver Quick TourThe following code snippets come from the NOTESee the installation guide for instructions on how to install the MongoDB Driver. Make a ConnectionThe following example shows five ways to connect to the database // To directly connect to a single MongoDB server// (this will not auto-discover the primary even if it's a member of a replica set)MongoClient mongoClient = new MongoClient();// orMongoClient mongoClient = new MongoClient( "localhost" );// orMongoClient mongoClient = new MongoClient( "localhost" , 27017 );// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of membersMongoClient mongoClient = new MongoClient( Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019)));// or use a connection stringMongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019"); MongoClient mongoClient = new MongoClient(connectionString); MongoDatabase database = mongoClient.getDatabase("mydb"); At this point, the MongoClientThe IMPORTANTTypically you only create one
Get a CollectionTo get a collection to operate upon, specify the name of the collection to the The following example gets the collection MongoCollection<Document> collection = database.getCollection("test"); Insert a DocumentOnce you have the collection object, you can insert documents into the collection. For example, consider the following JSON document; the document contains a field { "name" : "MongoDB", "type" : "database", "count" : 1, "info" : { x : 203, y : 102 } } To create the document using the Java driver, use the Document doc = new Document("name", "MongoDB") .append("type", "database") .append("count", 1) .append("info", new Document("x", 203).append("y", 102)); To insert the document into the collection, use the collection.insertOne(doc); Add Multiple DocumentsTo add multiple documents, you can use the The following example will add multiple documents of the form: { "i" : value } Create the documents in a loop. List<Document> documents = new ArrayList<Document>();for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } To insert these documents to the collection, pass the list of documents to the collection.insertMany(documents); Count Documents in A CollectionNow that we’ve inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the System.out.println(collection.count()); Query the CollectionUse the Find the First Document in a CollectionTo get the first document in the collection, call the The following example prints the first document found in the collection. Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); The example should print the following document: { "_id" : { "$oid" : "551582c558c7b4fbacf16735" }, "name" : "MongoDB", "type" : "database", "count" : 1, "info" : { "x" : 203, "y" : 102 } } NOTEThe Find All Documents in a CollectionTo retrieve all the documents in the collection, we will use the MongoCursor<Document> cursor = collection.find().iterator();try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } Although the following idiom is permissible, its use is discouraged as the application can leak a cursor if the loop terminates early: for (Document cur : collection.find()) { System.out.println(cur.toJson()); } Get A Single Document with a Query FilterWe can create a filter to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the “i” field is 71, we would do the following: import static com.mongodb.client.model.Filters.*; myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); and it should just print just one document { "_id" : { "$oid" : "5515836e58c7b4fbc756320b" }, "i" : 71 } NOTEUse the Get a Set of Documents with a QueryWe can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where // now use a range query to get a larger subsetBlock<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); Notice we use the We could also get a range, say collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); Sorting documentsWe can also use the myDoc = collection.find(exists("i")).sort(descending("i")).first(); System.out.println(myDoc.toJson()); Projecting fieldsSometimes we don’t need all the data contained in a document, the myDoc = collection.find().projection(excludeId()).first(); System.out.println(myDoc.toJson()); Updating documentsThere are numerous update operators supported by MongoDB. To update at most a single document (may be 0 if none match the filter), use the collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110))); To update all documents matching the filter use the UpdateResult updateResult = collection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100))); System.out.println(updateResult.getModifiedCount()); The update methods return an Deleting documentsTo delete at most a single document (may be 0 if none match the filter) use the collection.deleteOne(eq("i", 110)); To delete all documents matching the filter use the DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); The delete methods return a Bulk operationsThese new commands allow for the execution of bulk insert/update/delete operations. There are two types of bulk operations:
Let’s look at two simple examples using ordered and unordered operations: // 2. Ordered bulk operation - order is guarenteedcollection.bulkWrite( Arrays.asList(new InsertOneModel<>(new Document("_id", 4)), new InsertOneModel<>(new Document("_id", 5)), new InsertOneModel<>(new Document("_id", 6)), new UpdateOneModel<>(new Document("_id", 1), new Document("$set", new Document("x", 2))), new DeleteOneModel<>(new Document("_id", 2)), new ReplaceOneModel<>(new Document("_id", 3), new Document("_id", 3).append("x", 4)))); // 2. Unordered bulk operation - no guarantee of order of operationcollection.bulkWrite( Arrays.asList(new InsertOneModel<>(new Document("_id", 4)), new InsertOneModel<>(new Document("_id", 5)), new InsertOneModel<>(new Document("_id", 6)), new UpdateOneModel<>(new Document("_id", 1), new Document("$set", new Document("x", 2))), new DeleteOneModel<>(new Document("_id", 2)), new ReplaceOneModel<>(new Document("_id", 3), new Document("_id", 3).append("x", 4))), new BulkWriteOptions().ordered(false)); IMPORTANTUse of the bulkWrite methods is not recommended when connected to pre-2.6 MongoDB servers, as this was the first server version to support bulk write commands for insert, update, and delete in a way that allows the driver to implement the correct semantics for BulkWriteResult and BulkWriteException. The methods will still work for pre-2.6 servers, but performance will suffer, as each write operation has to be executed one at a time. |