这是一篇关于在java中操作mongodb的入门教程,包括创建连接,获取表,增加、删除、修改、查找等基础的功能,带你初步了解mongodb的基本操作的写法。
使用环境,注意mongodb3.0后的API有些已废除了:
1.mongodb 3.0.6
2.mongodb-java-driver 3.0.2
3.jdk1.6
4.maven 3.2.3
5.junit 4.7
6.Spring Tool Suite Version: 3.6.0.RELEASE
1.创建一个Spring MVC Maven项目并引入如下依赖,其他的用STS工具创建时会自动添加:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.0.2</version> </dependency>2.创建数据库连接及获取指定表(集合)对象
public static final int port = 27017; public static final String host = "127.0.0.1"; /** * 获取数据库对象 * * @return */ private MongoDatabase getDb() { // Old version, uses Mongo //Mongo mongo = new Mongo("localhost", 27017); // Since 2.10.0, uses MongoClient MongoClient mongo = new MongoClient(host, port); MongoDatabase db = mongo.getDatabase("new_db"); return db; } /** * 获取表(集合) * * @return */ private MongoCollection getCollection() { MongoDatabase db = getDb(); MongoCollection<Document> table = db.getCollection("user"); return table; }3.显示mongodb中的所有数据库
@Test public void displayDb() { MongoClient mongo = new MongoClient(host, port); MongoIterable<String> dbs= mongo.listDatabaseNames(); for (String name:dbs) { System.out.println(name); } }4.显示指定库下的所有的表(集合)
@Test public void displayTable() { MongoDatabase db = getDb(); MongoIterable<String> tables = db.listCollectionNames(); for (String name : tables) { System.out.println(name); } }5.保存实例
/** * 添加 */ @Test public void insert() { MongoCollection table = getCollection(); Document document = new Document(); document.put("name", "自成e家"); document.put("age", 20); document.put("createdDate", new Date()); table.insertOne(document); }
6.删除实例
/** * 删除 */ @Test public void delete() { MongoCollection table = getCollection(); Document document = new Document(); document.put("name", "自成e家"); DeleteResult result = table.deleteMany(document); assert (result.getDeletedCount() > 0); }7.更新实例
@Test public void update() { MongoCollection table = getCollection(); Document query = new Document(); query.put("name", "www.zicheng.net"); BasicDBObject newDoc = new BasicDBObject(); newDoc.put("name", "zicheng.net自成e家"); newDoc.put("age", 28); UpdateOptions options = new UpdateOptions(); //如果这里是true,当查不到结果的时候会添加一条newDoc,默认为false options.upsert(true); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", newDoc); UpdateResult result = table.updateMany(query, updateObj, options); assert result.getModifiedCount() > 0; }8.查询实例
/** * 查询 */ @Test public void find() { MongoCollection table = getCollection(); Document document = new Document(); document.put("age", 20); FindIterable iterable = table.find(document); MongoCursor cursor = iterable.iterator(); while (cursor.hasNext()) { Object o = cursor.tryNext(); System.out.println(o); } }以上就是mongodb在java中的基本增删改查操作,这里的操作与之前版本的有所不同,在测试的时候最好是用新版本的mongodb及驱动。
MongoDB JAVA Driver API文档参见:http://api.mongodb.org/java/3.0/