用java来写mongo
时间: 2023-12-29 21:03:55 浏览: 71
可能java上最好用而且实时跟进官方版本的ORM,让您更加舒适地使用MongoDMongoDBPlugin.zip
好的,以下是使用Java连接MongoDB并实现你所提出的需求的代码示例:
首先需要引入MongoDB Java Driver的依赖:
```xml
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.9</version>
</dependency>
```
然后可以按照以下步骤实现操作:
1. 导入必要的包:
```java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
```
2. 连接MongoDB数据库:
```java
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
```
3. 获取grade集合:
```java
MongoCollection<Document> collection = database.getCollection("grade");
```
4. 插入20条数据:
```java
String[] students = {"Tom", "Jack", "Jie", "Juliy", "Anma"};
String[] courses = {"Java", "BigData", "Math", "Python"};
for (int i = 0; i < 20; i++) {
String student = students[(int) (Math.random() * students.length)];
String course = courses[(int) (Math.random() * courses.length)];
int age = (int) (Math.random() * 7) + 15; // 15到21岁之间的随机年龄
Document document = new Document("student", student)
.append("course", course)
.append("age", age);
collection.insertOne(document);
}
```
5. 查询选修课程为“BigData”的学生信息:
```java
Document query = new Document("course", "BigData");
MongoCursor<Document> cursor = collection.find(query).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
```
完整代码如下:
```java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class Main {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("grade");
String[] students = {"Tom", "Jack", "Jie", "Juliy", "Anma"};
String[] courses = {"Java", "BigData", "Math", "Python"};
for (int i = 0; i < 20; i++) {
String student = students[(int) (Math.random() * students.length)];
String course = courses[(int) (Math.random() * courses.length)];
int age = (int) (Math.random() * 7) + 15; // 15到21岁之间的随机年龄
Document document = new Document("student", student)
.append("course", course)
.append("age", age);
collection.insertOne(document);
}
Document query = new Document("course", "BigData");
MongoCursor<Document> cursor = collection.find(query).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
mongoClient.close();
}
}
```
阅读全文