In the previous article, we talked about the MongoDB command entry. This blog will create a simple JavaMongoDBCRUDExample based on the database and table created in the previous blog, and connect to the MongoDB database using Java, it also implements routine operations such as creating databases, obtaining tables, traversing objects in tables, and performing CRUD operations on objects in tables. 1. Download MongoDBJav
In the previous article, we talked about the MongoDB command entry. This blog will complete a simple Java MongoDB CRUD Example based on the database and table created in the previous blog, and connect to the MongoDB database using Java, it also implements routine operations such as creating databases, obtaining tables, traversing objects in tables, and performing CRUD operations on objects in tables. 1. Download MongoDB Jav
In the previous article, we talked about the MongoDB command entry. This blog will complete a simple Java MongoDB CRUD Example based on the database and table created in the previous blog, and connect to the MongoDB database using Java, it also implements routine operations such as creating databases, obtaining tables, traversing objects in tables, and performing CRUD operations on objects in tables.
1. Download The MongoDB Java support driver package
[GitHub] https://github.com/mongodb/mongo-java-driver/downloads
2. Create a Java project and import the jar package
3. Connect to the Local Database Server
Enable the Mongodb service on the control panel. For more information about how to install and configure MongoDB, see [MongoDB database ].
Try {mongo = new MongoClient ("localhost", 27017); // ensure that the MongoDB service has started db = mongo. getDB ("andyDB"); // get database} catch (UnknownHostException e) {e. printStackTrace ();}
3. traverse all database names
Public class DBConnection extends TestCase {private writable client mongo; private DB db; @ Overrideprotected void setUp () throws Exception {// TODO Auto-generated method stubsuper. setUp (); try {mongo = new MongoClient ("localhost", 27017); // ensure that the MongoDB service has started db = mongo. getDB ("andyDB"); // get the database andyDB} catch (UnknownHostException e) {e. printStackTrace () ;}} public void testGetAllDB () {List
Dbs = mongo. getDatabaseNames (); // obtain all database names for (String dbname: dbs) {System. out. println (dbname );}}}
4. Obtain the specified database
DB db = mongo. getDB ("andyDB"); // obtain the database
5. traverse all the table names in the database
Add the following test method to the DBConnection test class:
public void testGetAllTables() {Set
tables = db.getCollectionNames();for (String coll : tables) {System.out.println(coll);}}
6. Get the specified table
DBCollection table = db.getCollection("person");
7. traverse all objects in the table
Public void testFindAll () {DBCollection table = db. getCollection ("person"); DBCursor dbCursor = table. find (); while (dbCursor. hasNext () {DBObject dbObject = dbCursor. next (); // print the object's specific field information System. out. println ("name:" + dbObject. get ("name") + ", age:" + dbObject. get ("age"); // print all information about the object System. out. println (dbObject );}}
Print messages in the Console window:
Name: jack and age: 50.0
{"_ Id": {"$ oid": "537761da2c82bf816b34e6cf"}, "name": "jack", "age": 50.0}
Name: Xiao Wang, age: 24
{"_ Id": {"$ oid": "53777096d67d552056ab8916"}, "name": "Xiao Wang", "age": 24}
8. Save the object
1) method 1 of saving objects
Public void testSave () {DBCollection table = db. getCollection ("person"); BasicDBObject document = new BasicDBObject (); document. put ("name", "Xiao Guo"); // you can insert a Chinese document directly. put ("age", 24); // The value corresponding to "age" is an int table. insert (document );}
Use commands in mongodb shell to view Data
> Db. person. find ()
{"_ Id": ObjectId ("537761da2c82bf816b34e6cf"), "name": "jack", "age": 50}
{"_ Id": ObjectId ("53777096d67d552056ab8916"), "name": "John", "age": 24}
{"_ Id": ObjectId ("5377712cd67d84f62c65c4f6"), "name": "guo", "age": 24}
2) method 2
Public void testSave2 () {DBCollection table = db. getCollection ("person"); BasicDBObject document = new BasicDBObject (); // you can add multiple fields to document. put ("name", "Xiaozhang"); // you can insert a Chinese document directly. put ("password", "xiaozhang"); // you can add another field because MongoDB saves the object; document. put ("age", "23"); // the value of "age" is Stringtable. insert (document );}
Use commands in mongodb shell to view Data
> Db. person. find ()
{"_ Id": ObjectId ("537761da2c82bf816b34e6cf"), "name": "jack", "age": 50}
{"_ Id": ObjectId ("53777096d67d552056ab8916"), "name": "John", "age": 24}
{"_ Id": ObjectId ("5377712cd67d84f62c65c4f6"), "name": "guo", "age": 24}
{"_ Id": ObjectId ("53777230d67dfe576de5079a"), "name": "Zhang", "password": "xiaozhang", "age": "23 "}
3) method 3 of saving objects(Add data to BasicDBObject by adding a Map set)
Public void testSave3 () {DBCollection table = db. getCollection ("person"); Map
Maps = new HashMap
(); Maps. put ("name", "Xiao Li"); maps. put ("password", "xiaozhang"); maps. put ("age", 24); BasicDBObject document = new BasicDBObject (maps); // after adding the object, the fields in the object are unordered. Table. insert (document );}
Use commands in mongodb shell to view Data
> Db. person. find ()
{"_ Id": ObjectId ("537761da2c82bf816b34e6cf"), "name": "jack", "age": 50}
{"_ Id": ObjectId ("53777096d67d552056ab8916"), "name": "John", "age": 24}
{"_ Id": ObjectId ("5377712cd67d84f62c65c4f6"), "name": "guo", "age": 24}
{"_ Id": ObjectId ("53777230d67dfe576de5079a"), "name": "Zhang", "password": "xiaozhang", "age": "23 "}
{"_ Id": ObjectId ("537772e9d67df098a26d79a6"), "age": 24, "name": "Xiao Li", "password": "xiaozhang "}
9. Update objects
We can combine the [mongodb shell command]Db. person. update ({name: "Xiao Li"}, {$ set: {password: "hello "}})To understand how Java operates on objects to update. {Name: "Xiao Li"} is a BasicDBObject. {$ set: {password: "hello"} is also a BasicDBObject. In this case, you will think that mongodb shell commands and Java operations are very similar.
Public void testUpdate () {DBCollection table = db. getCollection ("person"); BasicDBObject query = new BasicDBObject (); query. put ("name", "Xiao Zhang"); BasicDBObject newDocument = new BasicDBObject (); newDocument. put ("age", 23); BasicDBObject updateObj = new BasicDBObject (); updateObj. put ("$ set", newDocument); table. update (query, updateObj);} // command operation: db. person. update ({name: "Xiao Li" },{$ set: {password: "hello" }}) public void testUpdate2 () {DBCollection table = db. getCollection ("person"); BasicDBObject query = new BasicDBObject ("name", ""); BasicDBObject newDocument = new BasicDBObject ("age", 24 ); basicDBObject updateObj = new BasicDBObject ("$ set", newDocument); table. update (query, updateObj );}
10. Delete objects
You can refer to the db. users. remove ({name: "Xiao Li"}) command to Understand Java operation objects.
Public void testDelete () {DBCollection table = db. getCollection ("person"); BasicDBObject query = new BasicDBObject ("name", "Xiao Li"); table. remove (query );}
11. References
Java + MongoDB Hello World Example (recommended)
12. You may be interested
[MongoDB database] how to install and configure MongoDB
[MongoDB database] MongoDB command entry