更新时间:2023-09-05 GMT+08:00
访问数据库
具体访问数据库前,引入如下相关类。
import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import static com.mongodb.client.model.Filters.*; import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.ValidationOptions;
访问DataBase
当已经有一个初始化好的MongoClient实例后,通过如下方式来访问一个database,示例如下:
MongoDatabase database = mongoClient.getDatabase("test");
访问集合
当获取一个MongoDatabase实例后,可以通过如下命令来得到要获取的集合:
MongoCollection<Document> coll = database.getCollection("testCollection");
显示的创建一个集合
也可以通过 createCollection()方法显示的创建一个集合,并在创建时候指定该集合的属性。
database.createCollection("testCollection", new CreateCollectionOptions()..sizeInBytes(200000))
插入数据
Document doc0 = new Document("name", "zhangsan") .append("age", 3) .append("sex", "male"); Document doc1 = new Document("name", "LiSi") .append("age", 2) .append("sex", "female"); Document doc2 = new Document("name", "wangmazi") .append("age", 5) .append("sex", "male"); List<Document> documents = new ArrayList<Document>(); documents.add(doc1); documents.add(doc2); collection.insertMany(documents);
删除数据
collection.deleteOne(eq("_id", new ObjectId("00000001")));
删除表
MongoCollection<Document> collection = database.getCollection("test"); collection.drop()
读数据
MongoCollection<Document> collection = database.getCollection("contacts"); MongoCursor<String> cursor = collection.find(); while (cursor.hasNext()) { Object result = cursor.next(); }
带过滤条件的查询
MongoCollection<Document> collection = database.getCollection("test"); MongoCursor<String> cursor = collection.find( new Document("name","zhangsan") .append("age: 5)); while (cursor.hasNext()) { Object result = cursor.next(); }
运行命令
执行buildInfo和collStats
MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("test"); Document buildInfoResults = database.runCommand(new Document("buildInfo", 1)); System.out.println(buildInfoResults.toJson()); Document collStatsResults = database.runCommand(new Document("collStats", "restaurants")); System.out.println(collStatsResults.toJson());
创建建索引
MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("test"); collection.createIndex(Indexes.ascending("age"));
父主题: 基于Java开发