Created
April 3, 2015 16:44
-
-
Save dalmat36/fdc7907ab155cccc0216 to your computer and use it in GitHub Desktop.
This example shows how to perform some basic CRUD functions with MongoDB and the Java Driver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package mongoCrud; | |
| import static com.mongodb.client.model.Filters.eq; | |
| import org.bson.Document; | |
| import com.mongodb.MongoClient; | |
| import com.mongodb.client.MongoCollection; | |
| import com.mongodb.client.MongoCursor; | |
| import com.mongodb.client.MongoDatabase; | |
| public class MongoCrud { | |
| static MongoCollection<Document> collection; | |
| public static void main(String[] args) { | |
| MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); | |
| MongoDatabase database = mongoClient.getDatabase("mydb"); | |
| collection = database.getCollection("people"); | |
| collection.drop(); | |
| //Insert three famous person documents | |
| //Top 3 from http://www.biographyonline.net/people/famous-100.html | |
| Document person1 = new Document("First Name", "Marilyn") | |
| .append("Last Name", "Monroe"); | |
| Document person2 = new Document("First Name", "Abraham") | |
| .append("Last Name", "Lincoln"); | |
| Document person3 = new Document("First Name", "Mother") | |
| .append("Last Name", "Teresa"); | |
| collection.insertOne(person1); | |
| collection.insertOne(person2); | |
| collection.insertOne(person3); | |
| System.out.println("Result After Insert\n"); | |
| printAllPeople(); | |
| //Update a person document by Id | |
| Document updatedPerson = new Document("First Name", "Marilyn") | |
| .append("Last Name", "Monroe") | |
| .append("Description", "Actor"); | |
| collection.findOneAndReplace(eq("First Name", "Marilyn"), updatedPerson); | |
| System.out.println("Result After Update\n"); | |
| printAllPeople(); | |
| //Remove document from collection | |
| collection.deleteOne(eq("First Name", "Marilyn")); | |
| System.out.println("Result After Delete\n"); | |
| printAllPeople(); | |
| mongoClient.close(); | |
| } | |
| private static void printAllPeople(){ | |
| MongoCursor<Document> people = collection.find().iterator(); | |
| while(people.hasNext()) | |
| System.out.println(people.next()); | |
| System.out.println("\n"); | |
| people.close(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment