// 需要三個jar包,mongodb-driver-3.3.0.jar;mongodb-drvier-core-3.3.0.jar;bson-3.3.0.jar
public class MongoTest {
private MongoClient conn = null;
// 獲取連接
private MongoClient getConn() {
conn = new MongoClient("127.0.0.1", 27017);
return conn;
}
// 關閉連接
private void close(MongoClient conn) {
conn.close();
}
public void insert() {
conn = this.getConn();
// 獲取test數據庫,沒有自動創建
MongoDatabase db = conn.getDatabase("test");
// 獲取ss集合,沒有自動創建
MongoCollection<Document> collection = db.getCollection("ss");
// 創建文檔
Document doc = new Document("name", "lt").append("sex", "男").append("age", 30);
// 單量插入
collection.insertOne(doc);
// 批量插入
List<Document> docList = new ArrayList<Document>();
for (int i = 0; i < 20; i++) {
docList.add(new Document(..).append(..).append(..));
}
collection.insertMany(docList);
this.close(conn);
}
public int delete() {
conn = this.getConn();
MongoDatabase db = conn.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("ss");
// 單量刪除
collection.deleteOne(new Document("name", "new-lt10"));
// 批量刪除
DeleteResult deleteResult = collection.deleteMany(..);
this.close(conn);
// 返回影響文檔數
return deleteResult.getDeletedCount();
}
public int update() {
conn = this.getConn();
MongoDatabase db = conn.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("ss");
// 單量修改
collection.updateOne(new Document("name", "lt10"),
new Document("$set", new Document("name", "new-lt10")));
// 批量修改
UpdateResult updateResult = collection.updateMany(new Document("name", "lt10"),
new Document("$set", new Document("name", "new-lt10")));
this.close(conn);
return updateResult.getModifiedCount()
}
public void list() {
conn = this.getConn();
MongoDatabase db = conn.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("ss");
// 查詢集合大小
collection.count();
// 查詢集合的第一個文檔
Document myDoc = collection.find().first();
myDoc.toJson();
// 查詢集合的全部文檔
MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()) {
cursor.next().toJson();
}
// 查詢集合的全部文檔
for (Document cur : collection.find()) {
cur.toJson();
}
// 按條件查詢集合的指定文檔
MongoCursor<Document> cursor = collection.find(
new Document("name", "lt")).iterator();
while (cursor.hasNext()) {
cursor.next().toJson();
}
// 使用QueryBuilder按條件查詢,找到name叫lt,且sex爲man的記錄
QueryBuilder queryBuilder =
QueryBuilder.start("name").is("lt").and("set").is("man");
this.close(conn);
}
}
MongoDB的Java操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.