环境准备

jremongo-java-driver-2.13.3.jar

层级关系

数据库 集合 文档

maven:

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.2.2</version>
    </dependency>

Gradle:

compile group: 'org.mongodb', name: 'mongo-java-driver', version: '3.2.2'

连接MongoDB服务

MongoClient mongoClient = new MongoClient(ip,port);

连接到数据库

MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);

创建集合

mongoDatabase.createCollection(collectionName);

获取集合

MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection(collectionName);

插入文档

//插入一个文档
collection.insertOne(new Document("name","MongoDb")); 
//插入多个
Document document = new Document(key,value)
.append("name","MongoDB")
.append("type","DB")
.append("website","mongodb.com");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);

检索文档

获取迭代器、获取游标、使用游标遍历文档

 FindIterable<Document> findIterable = collection.find();  
 MongoCursor<Document> mongoCursor = findIterable.iterator();  
 while(mongoCursor.hasNext()){  
    System.out.println(mongoCursor.next());  
 } 

更新文档

collection.updateMany(Filters.eq("website","mongodb.com"),new Document("$set",new Document("website","https://www.mongodb.com")));

删除文档

//删除一个文档
collection.deleteOne(Filters.eq("name","MongoDB"));
//删除多个符合条件的文档
collection.deleteMany(Filters.eq("name","MongoDB"))

标签: MongoDB

添加新评论