如何从mongodb游标获取文档集合? [英] How to get collection of document from mongodb cursor?
问题描述
我有以下代码应该从 mongodb 返回一个文档列表.
I have the following code which should return a list of documents from mongodb.
struct Vehicle{
id: String,
name: String
}
pub async fn list_all() -> Vec<Vehicle>{
let mongodb = connection_bd::connection_mongodb().await;
let mongodb_collection = mongodb.collection("Vehicle");
let result = mongodb_collection.find(None, None).await; //result: Result<Cursor<Document>, Error>
let cursor = match result { //cursor: Cursor<Document>
Ok(x) => x,
Err(_) => return vec![]
};
//...
}
我无法完成代码,因为我不知道如何将Cursor
转换为Vec
,这是我第一次看到光标<文档>
,我不知道它是什么.
I can't finish the code because I don't know how to convert Cursor<Document>
to Vec<T>
, it's my first time seeing Cursor<Document>
and I don't know what it is.
更新
错误信息:
error[E0308]: mismatched types
--> src\vehicle_repo.rs:77:40
|
77 | pub async fn list_all() -> Vec<Vehicle>{
| ________________________________________^
78 | | let mongodb = connection_bd::connection_mongodb().await;
79 | | let mongodb_collection = mongodb.collection("Vehicle");
... |
84 | | };
85 | | }
| |_^ expected struct `Vec`, found `()`
|
= note: expected struct `Vec<Vehicle>`
found unit type `()`
推荐答案
一个 mongodb Cursor
实现了 futures
板条箱.docs 中提到了这一点:
A mongodb Cursor
implements Stream
from the futures
crate. This is mentioned in the docs:
此外,Stream
也可以在 Cursor
上使用.这包括 StreamExt提供的所有功能code>
,它提供了与标准库 Iterator
trait 类似的功能.例如,如果已知查询的结果数量很少,则将它们收集到一个向量中可能是有意义的:
Additionally, all the other methods that a
Stream
has are available onCursor
as well. This includes all of the functionality provided byStreamExt
, which provides similar functionality to the standard libraryIterator
trait. For instance, if the number of results from a query is known to be small, it might make sense to collect them into a vector:
let results: Vec<Result<Document>> = cursor.collect().await;
我实际上建议使用 TryStreamExt
trait 来获取 Result
代替.然后您可以使用 unwrap_or_else()
返回列表.您还应该使用 collection_with_type()
方法来获取集合,以便您的结果将自动反序列化为正确的类型,而不仅仅是 Document
(只需确保它实现了 Debug
、Serialize
和 Deserialize
).
I would actually recommend using the try_collect()
function from the TryStreamExt
trait to get a Result<Vec<Document>>
instead. Then you can use unwrap_or_else()
to return the list. You should also use the collection_with_type()
method to get the collection so that your results will be automatically deserialized to the proper type instead of just Document
(just make sure it implements Debug
, Serialize
and Deserialize
).
这是一个工作示例
use futures::TryStreamExt;
use mongodb::Client;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Vehicle {
id: String,
name: String,
}
async fn list_all() -> Vec<Vehicle> {
let client = Client::with_uri_str("mongodb://example.com").await.unwrap();
let database = client.database("test");
let collection = database.collection_with_type::<Vehicle>("vehicles");
let cursor = match collection.find(None, None).await {
Ok(cursor) => cursor,
Err(_) => return vec![],
};
cursor.try_collect().await.unwrap_or_else(|_| vec![])
}
这篇关于如何从mongodb游标获取文档集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!