1. 程式人生 > >java對mongoDB 的基本操作

java對mongoDB 的基本操作

  • 獲取連結
MongoClient client = MongoDBConnection.getInstance("192.168.128.104", 27017);
  • 獲取資料庫
MongoDatabase mongoDatabase = client.getDatabase(database);
  • 建立文件集合
mongoDatabase.createCollection(collection);
  • 獲取文件集合
MongoCollection< Document> collection=database.getCollection("users"
); //設定查詢條件 Bson filterBson = Filters.gte("sul1", "sul1"); Bson filter2 = Filters.gte("xul2", "xul2"); //多個條件組合 Bson bson = Filters.and(filter2,filterBson); FindIterable< Document> result = collection.find(bson); for(Document doc : result){ System.out.println(doc.get("sul1")); }
  • 文件新增操作
Document document = new
Document(); document.append("sul1", "sul1").append("xul2", "xul2"); List<Document> list = new ArrayList<Document>(); list.add(document); MongoDatabase database = this.getMongoDataBase("xul"); MongoCollection< Document> collection = database.getCollection("users"); collection.insertMany(list
);
  • 排序並查詢一條資料
MongoCollection table = getCollection();
BasicDBObject dbObject = new BasicDBObject();
//mongodb中按age欄位倒序查詢(-1是倒序,1是正序)
dbObject.put("age",-1);
FindIterable iterate =table.find().sort(dbObject).limit(1);
  • 分頁查詢
int pageSize = 3;
MongoCollection table = getCollection();
//mongodb分頁查詢出遊標
MongoCursor cursor = table.find().limit(pageSize).skip((pageIndex - 1) * pageSize).iterator();
System.out.println("當前頁:" + pageIndex);
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}
  • 顯示資料庫中的所有資料
public void displayDb()
 {
     MongoClient mongo = new MongoClient(host, port);
    MongoIterable<String> dbs= mongo.listDatabaseNames();
     for (String name:dbs)
     {
         System.out.println(name);
     }
 }
  • 獲取指定庫下的所有集合
 public void displayTable() {
     MongoDatabase db = getDb();
     MongoIterable<String> tables = db.listCollectionNames();
     for (String name : tables) {
         System.out.println(name);
     }
 }
  • 刪除操作
public void delete() {
     MongoCollection table = getCollection();
     Document document = new Document();
     document.put("name", "xul");
     DeleteResult result = table.deleteMany(document);
 }
  • 更新操作
    public void updateDocument(){
        MongoCollection<Document> collection = this.getCollection();        
        BasicDBObject upda = new BasicDBObject();
        upda.append("xul2", "testupdatexul");   
        BasicDBObject object = new BasicDBObject();
        object.append("$set", upda);
        collection.updateOne(Filters.gte("sul1", "sul1"), object);          
    }