java连接mongodb 1.新建一个数据库javamongotest 2.新建两个集合(user和owner),信息如下,要求:同时插入多个文档(insertMany) { "name" : “xiuxiu", "hobby" : "piano", “times”:6 } { "name" : chongyu", "hobby" : "basketball", “times”:5 } { "name" : "ruizhi", "hobby" : "books" “times”:3 }, { "name" :” yixin", "hobby" : " drawing" “times”:4 } { "name" : “yufeng", "hobby" : "music" “times”:6 } 2.向student集合插入如下文档 { "name" : “kefan", "hobby":”cloud computing”, times:1 } 3.统计文档user集合中的文档数量 4.查询name为kefan的文档,添加一个hobby属性 "likes":”helping others” 5.使用{name:"科凡"} 替换 name 为kefan 的文档 6.查询times>=5的user信息,并删除
时间: 2023-07-03 13:04:51 浏览: 99
以下是 Java 连接 MongoDB 并完成上述任务的代码:
```java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoDBTest {
public static void main(String[] args) {
//连接MongoDB
MongoClient mongoClient = new MongoClient("localhost", 27017);
//获取数据库
MongoDatabase db = mongoClient.getDatabase("javamongotest");
//获取集合
MongoCollection<Document> userCollection = db.getCollection("user");
MongoCollection<Document> ownerCollection = db.getCollection("owner");
//同时插入多个文档
List<Document> userList = new ArrayList<>();
userList.add(new Document("name", "xiuxiu").append("hobby", "piano").append("times", 6));
userList.add(new Document("name", "chongyu").append("hobby", "basketball").append("times", 5));
userList.add(new Document("name", "ruizhi").append("hobby", "books").append("times", 3));
userList.add(new Document("name", "yixin").append("hobby", "drawing").append("times", 4));
userList.add(new Document("name", "yufeng").append("hobby", "music").append("times", 6));
userCollection.insertMany(userList);
//向student集合插入文档
Document studentDoc = new Document("name", "kefan").append("hobby", "cloud computing").append("times", 1);
db.getCollection("student").insertOne(studentDoc);
//统计文档user集合中的文档数量
long count = userCollection.countDocuments();
System.out.println("user集合中的文档数量为:" + count);
//查询name为kefan的文档,添加一个hobby属性"likes":"helping others"
Document kefanDoc = db.getCollection("student").find(Filters.eq("name", "kefan")).first();
kefanDoc.append("likes", "helping others");
db.getCollection("student").replaceOne(Filters.eq("name", "kefan"), kefanDoc);
//使用{name:"科凡"}替换name为kefan的文档
db.getCollection("student").replaceOne(Filters.eq("name", "kefan"),
new Document("name", "科凡").append("hobby", "cloud computing").append("times", 1));
//查询times>=5的user信息,并删除
List<Document> userListToDelete = userCollection.find(Filters.gte("times", 5)).into(new ArrayList<>());
for (Document doc : userListToDelete) {
userCollection.deleteOne(doc);
}
//关闭MongoDB连接
mongoClient.close();
}
}
```
需要注意的是,上述代码需要先导入以下依赖:
```xml
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.7</version>
</dependency>
```
阅读全文