"MongoDB database" Java MongoDB CRUD Example

Source: Internet
Author: User
Tags mongoclient



In the previous article, we talked about MongoDB's command to get started, this blog will be based on the previous blog created database and table completed a simple Java MongoDB CRUD Example, using Java to connect MongoDB database. and implement routines such as creating a database, getting a table, traversing objects in a table, and CRUD operations on objects in a table.



1. Download MongoDB Java Support driver package



"GitHub" Https://github.com/mongodb/mongo-java-driver/downloads



2, build Javaproject, and import jar package



3. Connect to local database server



Open MongoDB Service in Control Panel, detailed operation can refer to "MongoDB database" How to install, configure MongoDB


try {
mongo = new MongoClient ("localhost", 27017); // Ensure that the MongoDB service is started
db = mongo.getDB ("andyDB"); // Get the database
} catch (UnknownHostException e) {
e.printStackTrace ();
}


3. Traverse all database names





public class DBConnection extends TestCase {

private MongoClient mongo;
private DB db;

@Override
protected void setUp () throws Exception {
// TODO Auto-generated method stub
super.setUp ();
try {
mongo = new MongoClient ("localhost", 27017); // Ensure that the MongoDB service is started
db = mongo.getDB ("andyDB"); // Get the database andyDB
} catch (UnknownHostException e) {
e.printStackTrace ();
}
}

public void testGetAllDB () {
List <String> dbs = mongo.getDatabaseNames (); // Get all database names
for (String dbname: dbs) {
System.out.println (dbname);
}
}
}





4. Get to the specified database





       DB db = Mongo.getdb ("Andydb");//Get to Database





5. Iterate through all the table names in the database



The following test methods can be added to the DbConnection test class, for example:





public void testGetAllTables() {
		Set<String> tables = db.getCollectionNames();
		for (String coll : tables) {
			System.out.println(coll);
		}
	}





6. Get to the specified table




Dbcollection table = db.getcollection ("person");





7. Iterate through all the 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 specific field information of the object
System.out.println ("name:" + dbObject.get ("name") + ", age:" + dbObject.get ("age"));
// Print all information of the object
System.out.println (dbObject);
}
}





Console form to print messages:



name:jack,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 Objects



1) Save Object Method One




public void testSave () {
DBCollection table = db.getCollection ("person");
BasicDBObject document = new BasicDBObject ();
document.put ("name", "小郭"); // Can insert Chinese characters directly
document.put ("age", 24); // The corresponding value of "age" is int
table.insert (document);
}
Using commands to view data in a MongoDB shell





> Db.person.find ()
{"_id": ObjectId ("537761DA2C82BF816B34E6CF"), "name": "Jack", "Age": 50}
{"_id": ObjectId ("53777096d67d552056ab8916"), "name": "Xiao Wang", "Age": 24}
{"_id": ObjectId ("5377712cd67d84f62c65c4f6"), "name": "Xiao Guo", "Age": 24}



2) Save Object Method Two




public void testSave2 () {
DBCollection table = db.getCollection ("person");
BasicDBObject document = new BasicDBObject (); // Can add multiple fields
document.put ("name", "小张"); // Can insert Chinese characters directly
document.put ("password", "xiaozhang"); // It is also possible to add one more field, because MongoDB stores objects.
document.put ("age", "23"); // The corresponding value of "age" is String
table.insert (document);
}





Using commands to view data in a MongoDB shell



> Db.person.find ()
{"_id": ObjectId ("537761DA2C82BF816B34E6CF"), "name": "Jack", "Age": 50}
{"_id": ObjectId ("53777096d67d552056ab8916"), "name": "Xiao Wang", "Age": 24}
{"_id": ObjectId ("5377712cd67d84f62c65c4f6"), "name": "Xiao Guo", "Age": 24}
{"_id": ObjectId ("53777230d67dfe576de5079a"), "name": "Xiao Zhang", "Password": "Xiaozhang", "Age": "23"}



3) Save Object Method Three ( add data to Basicdbobject by adding a map collection)




public void testSave3 () {
DBCollection table = db.getCollection ("person");
Hell
Map <String, Object> maps = new HashMap <String, Object> ();
maps.put ("name", "Xiao Li");
maps.put ("password", "xiaozhang");
maps.put ("age", 24);
Hell
BasicDBObject document = new BasicDBObject (maps); // After adding this. The fields in the object are out of order.
table.insert (document);
}





Using commands to view data in a MongoDB shell



> Db.person.find ()
{"_id": ObjectId ("537761DA2C82BF816B34E6CF"), "name": "Jack", "Age": 50}
{"_id": ObjectId ("53777096d67d552056ab8916"), "name": "Xiao Wang", "Age": 24}
{"_id": ObjectId ("5377712cd67d84f62c65c4f6"), "name": "Xiao Guo", "Age": 24}
{"_id": ObjectId ("53777230d67dfe576de5079a"), "name": "Xiao Zhang", "Password": "Xiaozhang", "Age": "23"}
{"_id": ObjectId ("537772e9d67df098a26d79a6"), "age": +, "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 is manipulating objects to be updated. {name: "Xiao Li"} is a basicdbobject. {$set: {password: ' Hello '} is also a basicdbobject. Understand the words so. You would think that MongoDB shell command operations are very similar to Java operations.




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: "小李"}, {$ set: {password: "hello"}})
public void testUpdate2 () {
DBCollection table = db.getCollection ("person");
BasicDBObject query = new BasicDBObject ("name", "Xiao Zhang");
BasicDBObject newDocument = new BasicDBObject ("age", 24);
BasicDBObject updateObj = new BasicDBObject ("$ set", newDocument);
table.update (query, updateObj);
}





10. Deleting objects



Db.users.remove ({name: "Xiao Li"}) command to understand Java operations 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 in



How the MongoDB database installs, configures MongoDB



A probe into the MongoDB database MongoDB command Getting Started



Reprint Please specify source: http://blog.csdn.net/andie_guo/article/details/26098331, thank you!



"MongoDB database" Java MongoDB CRUD Example


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.