上一篇我们讲了MongoDB 的命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完成一个简单的Java MongoDB CRUD Example,利用Java连接MongoDB数据库,并实现创建数据库、获取表、遍历表中的对象、对表中对象进行CRUD操作等例程。 1、下载MongoDB Jav
上一篇我们讲了MongoDB 的命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完成一个简单的Java MongoDB CRUD Example,利用Java连接MongoDB数据库,并实现创建数据库、获取表、遍历表中的对象、对表中对象进行CRUD操作等例程。
1、下载MongoDB Java 支持驱动包
【gitHub下载地址】https://github.com/mongodb/mongo-java-driver/downloads
2、建立Java工程,并导入jar包
3、连接本地数据库服务器
在控制面板中开启Mongodb服务,具体操作可参考【MongoDB数据库】如何安装、配置MongoDB
try { mongo = new MongoClient("localhost", 27017);// 保证MongoDB服务已经启动 db = mongo.getDB("andyDB");// 获取到数据库 } catch (UnknownHostException e) { e.printStackTrace(); }
3、遍历所有的数据库名
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);// 保证MongoDB服务已经启动 db = mongo.getDB("andyDB");// 获取到数据库andyDB } catch (UnknownHostException e) { e.printStackTrace(); } } public void testGetAllDB() { List<String> dbs = mongo.getDatabaseNames();// 获取到所有的数据库名 for (String dbname : dbs) { System.out.println(dbname); } } }
4、获取到指定数据库
DB db = mongo.getDB("andyDB");// 获取到数据库
5、遍历数据库中所有的表名
在DBConnection测试类中添加如下测试方法即可:
public void testGetAllTables() { Set<String> tables = db.getCollectionNames(); for (String coll : tables) { System.out.println(coll); } }
6、获取到指定的表
DBCollection table = db.getCollection("person");
7、遍历表中所有的对象
public void testFindAll(){ DBCollection table = db.getCollection("person"); DBCursor dbCursor = table.find(); while(dbCursor.hasNext()){ DBObject dbObject = dbCursor.next(); //打印该对象的特定字段信息 System.out.println("name:"+ dbObject.get("name")+",age:"+dbObject.get("age")); //打印该对象的所有信息 System.out.println(dbObject); } }
Console窗口打印消息:
name:jack,age:50.0
{ "_id" : { "$oid" : "537761da2c82bf816b34e6cf"} , "name" : "jack" , "age" : 50.0}
name:小王,age:24
{ "_id" : { "$oid" : "53777096d67d552056ab8916"} , "name" : "小王" , "age" : 24}
8、保存对象
1)保存对象方法一
public void testSave() { DBCollection table = db.getCollection("person"); BasicDBObject document = new BasicDBObject(); document.put("name", "小郭");// 能直接插入汉字 document.put("age", 24);//"age"对应的值是int型 table.insert(document); }在mongodb shell中使用命令查看数据
> db.person.find()
{ "_id" : ObjectId("537761da2c82bf816b34e6cf"), "name" : "jack", "age" : 50 }
{ "_id" : ObjectId("53777096d67d552056ab8916"), "name" : "小王", "age" : 24 }
{ "_id" : ObjectId("5377712cd67d84f62c65c4f6"), "name" : "小郭", "age" : 24 }
2)保存对象方法二
public void testSave2() { DBCollection table = db.getCollection("person"); BasicDBObject document = new BasicDBObject();//可以添加多个字段 document.put("name", "小张");// 能直接插入汉字 document.put("password", "xiaozhang");// 多添加一个字段也是可以的,因为MongoDB保存的是对象; document.put("age", "23");//"age"对应的值是String table.insert(document); }
在mongodb shell中使用命令查看数据
> db.person.find()
{ "_id" : ObjectId("537761da2c82bf816b34e6cf"), "name" : "jack", "age" : 50 }
{ "_id" : ObjectId("53777096d67d552056ab8916"), "name" : "小王", "age" : 24 }
{ "_id" : ObjectId("5377712cd67d84f62c65c4f6"), "name" : "小郭", "age" : 24 }
{ "_id" : ObjectId("53777230d67dfe576de5079a"), "name" : "小张", "password" : "xiaozhang", "age" : "23" }
3)保存对象方法三(通过添加Map集合的方式添加数据到BasicDBObject)
public void testSave3(){ DBCollection table = db.getCollection("person"); Map<String,Object> maps = new HashMap<String,Object>(); maps.put("name", "小李"); maps.put("password", "xiaozhang"); maps.put("age", 24); BasicDBObject document = new BasicDBObject(maps);//这样添加后,对象里的字段是无序的。 table.insert(document); }
在mongodb shell中使用命令查看数据
> db.person.find()
{ "_id" : ObjectId("537761da2c82bf816b34e6cf"), "name" : "jack", "age" : 50 }
{ "_id" : ObjectId("53777096d67d552056ab8916"), "name" : "小王", "age" : 24 }
{ "_id" : ObjectId("5377712cd67d84f62c65c4f6"), "name" : "小郭", "age" : 24 }
{ "_id" : ObjectId("53777230d67dfe576de5079a"), "name" : "小张", "password" : "xiaozhang", "age" : "23" }
{ "_id" : ObjectId("537772e9d67df098a26d79a6"), "age" : 24, "name" : "小李", "password" : "xiaozhang" }
9、更新对象
我们可以结合【mongodb shell命令】db.person.update({name:"小李"},{$set:{password:"hello"}})来理解Java是如何操作对象来更新的。{name:"小李"}是一个BasicDBObject,{$set:{password:"hello"}也是一个BasicDBObject,这样理解的话,你就会觉得mongodb shell命令操作和Java操作很相似。
public void testUpdate() { DBCollection table = db.getCollection("person"); BasicDBObject query = new BasicDBObject(); query.put("name", "小张"); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("age", 23); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", newDocument); table.update(query, updateObj); } // 命令操作:db.person.update({name:"小李"},{$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、删除对象
可参考db.users.remove({name:"小李"})命令来理解Java操作对象
public void testDelete(){ DBCollection table = db.getCollection("person"); BasicDBObject query = new BasicDBObject("name", "小李"); table.remove(query); }
11、参考
Java + MongoDB Hello World Example(推荐)
12、你可能感兴趣
【MongoDB数据库】如何安装、配置MongoDB
【MongoDB数据库】MongoDB 命令入门初探

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
