Java操作MongoDB
阿新 • • 發佈:2017-05-26
mongodb
先引入mongo-java-dirver驅動
<!-- mongo-java-dirver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.4.2</version> </dependency>
代碼操作演示:
package com.simple.database.test; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; /** * java操作MongoDB * @author root */ public class HelloMongoDB { public static void main(String[] args) { try { // 1、連接到MongoDB服務 MongoClient mc = new MongoClient("127.0.0.1", 27017); // 2、連接到指定數據庫 MongoDatabase db = mc.getDatabase("demodb"); // 3、創建集合 // db.createCollection("simplelife"); // 4、獲取集合 MongoCollection<Document> collection = db.getCollection("users"); // 5、插入文檔數據 // insertCollectionData(collection); // 6、查詢文檔數據 findCollectionData(collection); // 7、更新文檔數據 // 將文檔中likes=100的文檔修改為likes=200 updateCollectionData(collection); // 8、刪除第一個文檔數據 collection.deleteMany(Filters.eq("likes",200)); collection.deleteOne(Filters.eq("likes",100)); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getClass().getName() + "……" + e.getMessage()); } } private static void updateCollectionData( MongoCollection<Document> collection) { Bson filter = Filters.eq("likes", 100); Document update = new Document("$set", new Document("likes", 200)); collection.updateMany(filter, update); } private static void findCollectionData(MongoCollection<Document> collection) { FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } } /** * 插入文檔 1、創建文檔org.bson.Document參數為key-value的格式 * 2、創建文檔集合List<Document> * 3、將文檔集合插入數據庫集合:mongoCollection.insertMany(List<Document>) * 插入單個文檔可以用 :mongoCollection.insertOne(Document) */ private static void insertCollectionData( MongoCollection<Document> collection) { Document document = new Document("title", "MongoDB"); document.append("description", "database").append("likes", 100) .append("by", "Fly"); List<Document> documents = new ArrayList<>(); documents.add(document); collection.insertMany(documents); System.out.println("文檔插入成功!"); } }
本文出自 “SimpleLife” 博客,請務必保留此出處http://simplelife.blog.51cto.com/9954761/1929886
Java操作MongoDB