mongodb objetcid_mongoDB Java SDK CRUD操作例子
时间: 2023-07-04 22:28:55 浏览: 113
以下使用MongoDB Java SDK进行CRUD操作的示例:
1. 连接到MongoDB数据库
```
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("mydb");
```
2. 插入数据
```
MongoCollection<Document> collection = database.getCollection("mycollection");
Document document = new Document("name", "John Doe")
.append("age", 30)
.append("email", "johndoe@example.com");
collection.insertOne(document);
```
3. 查询数据
```
MongoCollection<Document> collection = database.getCollection("mycollection");
Document query = new Document("name", "John Doe");
FindIterable<Document> results = collection.find(query);
for (Document result : results) {
System.out.println(result.toJson());
}
```
4. 更新数据
```
MongoCollection<Document> collection = database.getCollection("mycollection");
Document query = new Document("name", "John Doe");
Document update = new Document("$set", new Document("age", 35));
collection.updateOne(query, update);
```
5. 删除数据
```
MongoCollection<Document> collection = database.getCollection("mycollection");
Document query = new Document("name", "John Doe");
collection.deleteOne(query);
```
注意:以上代码只是示例,实际使用时需要根据具体情况进行修改。
阅读全文