在其他类中调用 public List<Document> get(MongoCollection<Document> collection,String key,String value){ List<Document> resultList=new ArrayList<Document>(); collection.find(Filters.eq(key, value)).into(resultList); return resultList; }方法
时间: 2023-12-10 19:41:48 浏览: 34
如果你想在其他类中调用这个方法,你需要将这个方法声明为public static,这样其他类才能够直接调用它,而不需要先创建一个对象。
以下是修改后的代码示例:
```
public static List<Document> get(MongoCollection<Document> collection, String key, String value) {
List<Document> resultList = new ArrayList<Document>();
collection.find(Filters.eq(key, value)).into(resultList);
return resultList;
}
```
现在你可以在其他类中直接使用类名.方法名的方式调用这个方法,例如:
```
List<Document> resultList = YourClassName.get(collection, "name", "John");
```
相关问题
public List<Document> get(MongoCollection<Document> collection,String key,String value)
这是一个 Java 方法,它使用 MongoDB Java 驱动程序获取指定集合中所有具有指定键值对的文档。它接受三个参数:MongoCollection 对象,用于指定所需集合;key,用于指定要查找的字段;value,用于指定要查找的字段值。它返回一个 List<Document> 对象,其中包含所有匹配的文档。
以下是该方法的示例代码:
```
public List<Document> get(MongoCollection<Document> collection,String key,String value) {
BasicDBObject query = new BasicDBObject(key, value);
FindIterable<Document> iterable = collection.find(query);
List<Document> result = new ArrayList<Document>();
for (Document document : iterable) {
result.add(document);
}
return result;
}
```
怎么调用 public List<Document> get(MongoCollection<Document> collection,String key,String value){ List<Document> resultList=new ArrayList<Document>(); collection.find(Filters.eq(key, value)).into(resultList); return resultList; }
这个方法是用来从 MongoDB 数据库中查询符合指定键值对的文档。
你可以按照以下步骤来调用这个方法:
1. 首先,你需要创建一个 `MongoClient` 对象,以连接到 MongoDB 数据库。你可以使用如下代码创建一个 MongoClient 对象:
```java
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
```
这里假设 MongoDB 数据库运行在本地机器上,端口号为 27017。
2. 接下来,你需要获取到要查询的集合。假设你要查询的集合名为 `myCollection`,你可以使用如下代码获取这个集合的引用:
```java
MongoCollection<Document> collection = mongoClient.getDatabase("myDatabase").getCollection("myCollection");
```
这里假设你要查询的集合所在的数据库名为 `myDatabase`。
3. 最后,你可以调用 `get()` 方法来查询符合指定键值对的文档。例如,如果你要查询 `myCollection` 集合中 `name` 字段为 `"Alice"` 的文档,你可以使用以下代码:
```java
List<Document> resultList = get(collection, "name", "Alice");
```
这个方法会返回一个包含所有符合条件的文档的列表。你可以遍历这个列表来处理查询结果。