Make a Connection
Following example shows ways to connect to the database mydb on the local machine. If the database does not exist, MongoDB will create it for you.
- // 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();
- // or
- MongoClient mongoClient = new MongoClient( "localhost" );
- // or
- MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
- // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
- MongoClient mongoClient = new MongoClient(
- Arrays.asList(new ServerAddress("localhost", 27017),
- new ServerAddress("localhost", 27018),
- new ServerAddress("localhost", 27019)));
- // or use a connection string
- MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");
- MongoClient mongoClient = new MongoClient(connectionString);
- MongoDatabase database = mongoClient.getDatabase("mydb");
MongoClient
The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads. Typically you only create one MongoClient instance for a given database cluster and use it across your application. When creating multiple instances:
Get a Collection
To get a collection to operate upon, specify the name of the collection to the getCollection() method from object which implement MongoDatabase interface. The following example gets the collection test:
- MongoCollection
collection = database.getCollection( "test");
Once you have the collection object (MongoCollection), you can insert documents into the collection. For example, consider the following JSON document; the document contains a field info which is an embedded document:
- {
- "name" : "MongoDB",
- "type" : "database",
- "count" : 1,
- "info" : {
- x : 203,
- y : 102
- }
- }
- Document doc = new Document("name", "MongoDB")
- .append("type", "database")
- .append("count", 1)
- .append("info", new Document("x", 203).append("y", 102));
- collection.insertOne(doc);
To add multiple documents, you can use the insertMany() method. The following example will add multiple documents of the form:
- { "i" : value }
- List
documents = new ArrayList(); - for (int i = 0; i < 100; i++) {
- documents.add(new Document("i", i));
- }
- collection.insertMany(documents);
Now 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 count() method. The following code should print 101.
- System.out.println(collection.count());
Use the find() method to query the collection.
Find the First Document in a Collection
To get the first document in the collection, call the first() method on the find() operation. collection.find().first() returns the first document or null rather than a cursor. This is useful for queries that should only match a single document, or if you are interested in the first document only.
The following example prints the first document found in the collection.
- Document myDoc = collection.find().first();
- System.out.println(myDoc.toJson());
- { "_id" : { "$oid" : "551582c558c7b4fbacf16735" },
- "name" : "MongoDB", "type" : "database", "count" : 1,
- "info" : { "x" : 203, "y" : 102 } }
Find All Documents in a Collection
To retrieve all the documents in the collection, we will use the find() method. The find() method returns a FindIterable instance that provides a fluent interface for chaining or controlling find operations. Use the iterator() method to get an iterator over the set of documents that matched the query and iterate. The following code retrieves all documents in the collection and prints them out (101 documents):
- MongoCursor
cursor = collection.find().iterator(); - try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next().toJson());
- }
- } finally {
- cursor.close();
- }
- for (Document cur : collection.find()) {
- System.out.println(cur.toJson());
- }
We 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());
- { "_id" : { "$oid" : "5515836e58c7b4fbc756320b" }, "i" : 71 }
Get a Set of Documents with a Query
We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:
- // now use a range query to get a larger subset
- Block
printBlock = new Block () { - @Override
- public void apply(final Document document) {
- System.out.println(document.toJson());
- }
- };
- collection.find(gt("i", 50)).forEach(printBlock);
- collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
We can also use the Sorts helpers to sort documents. We add a sort to a find query by calling the sort() method on a FindIterable. Below we use theBelow we use the }}"="" target="_new" rel="nofollow" style="color: rgb(1, 51, 107); text-decoration: none; font-family: verdana, arial, helvetica, sans-serif; font-size: 12px; line-height: 18px; background-color: rgb(250, 250, 250);">exists()helper and sort descending("i") helper to sort our documents:
- myDoc = collection.find(exists("i")).sort(descending("i")).first();
- System.out.println(myDoc.toJson());
Sometimes we don’t need all the data contained in a document, the Projections helpers help build the projection parameter for the find operation. Below we’ll sort the collection, exclude the _id field and output the first matching document:
- myDoc = collection.find().projection(excludeId()).first();
- System.out.println(myDoc.toJson());
There are numerous update operators supported by MongoDB.
To update at most a single document (may be 0 if none match the filter), use the updateOne method to specify the filter and the update document. Here we update the first document that meets the filter i equals 10 and set the value of i to 110:
- collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));
- UpdateResult updateResult = collection.updateMany(lt("i", 100),
- new Document("$inc", new Document("i", 100)));
- System.out.println(updateResult.getModifiedCount());
Deleting documents
To delete at most a single document (may be 0 if none match the filter) use the deleteOne method:
- collection.deleteOne(eq("i", 110));
- DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
- System.out.println(deleteResult.getDeletedCount());
Bulk operations
These 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:
- // 1. Ordered bulk operation - order is guarenteed
- collection.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 operation
- collection.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));
* Getting Started - Java Driver
* Getting Started - Insert Data
* Getting Started - Find Or Query Data
* Getting Started - Update Data
* Getting Started - Remove Data
* Getting Started - Data Aggregation
沒有留言:
張貼留言