In the previous article we talked about MongoDB's command to get started, this blog will be based on the database and table established in the previous blog to complete a simple Java MongoDB CRUD Example, the use of Java to connect MongoDB database, and the implementation of database creation, get the table, Routines such as traversing objects in a table, CRUD operations on objects in a table, and so on.
1. Download MongoDB Java Support driver package
"GitHub" Https://github.com/mongodb/mongo-java-driver/downloads
2. Build Java project and import jar package
3. Connect the Local database server
Open the MongoDB service in the control Panel, and refer to "MongoDB database" How to install and 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. Traverse all table names in the database
Add the following test method to the DbConnection test class:
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. 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 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);
}
}
The console window prints the message:
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 value corresponding to "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 value corresponding to "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");
Ranch
Map <String, Object> maps = new HashMap <String, Object> ();
maps.put ("name", "Xiao Li");
maps.put ("password", "xiaozhang");
maps.put ("age", 24);
Ranch
BasicDBObject document = new BasicDBObject (maps); // After this is added, 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 update. {name: "Xiao Li"} is a basicdbobject,{$set: {password: "Hello"} is also a basicdbobject, so to understand, you will feel the MongoDB Shell command operation and Java operation is 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: "小李"}, {$ 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
You can refer to the Db.users.remove ({name: "Xiao Li"}) command to understand the Java Action object
public void testDelete(){
DBCollection table = db.getCollection("person");
BasicDBObject query = new BasicDBObject("name", "小李");
table.remove(query);
}
11. Reference
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!