gpt4 book ai didi

mongodb - 如何从 mongodb 游标获取文档集合?

转载 作者:行者123 更新时间:2023-12-05 02:43:06 28 4
gpt4 key购买 nike

我有以下代码,它应该从 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<Document>Vec<T> ,我还是第一次见Cursor<Document>我不知道它是什么。

已更新
错误信息:

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工具 Stream来自 futures crate . docs 中提到了这一点:

Additionally, all the other methods that a Stream has are available on Cursor as well. This includes all of the functionality provided by StreamExt, which provides similar functionality to the standard library Iterator 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;

我实际上会推荐使用 try_collect()来自 TryStreamExt 的函数获得 Result<Vec<Document>> 的特质反而。然后你可以使用unwrap_or_else()返回列表。您还应该使用 collection_with_type()获取集合的方法,以便您的结果将自动反序列化为正确的类型,而不仅仅是 Document (只需确保它实现了 DebugSerializeDeserialize )。

这是一个工作示例

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 - 如何从 mongodb 游标获取文档集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67036017/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com