mongodb - 如何在 Rust 中使用 Mongodb::cursor?

学习如何将 mongodb 与 Rust 结合使用是一个非常简单的项目。我在这里使用官方的 mongodb 驱动程序:https://github.com/mongodb/mongo-rust-driver .问题是如果我使用 aggregate , 我无法读取结果

// main.rs
use mongodb::bson::{doc, Bson};
use mongodb::{options::AggregateOptions, options::ClientOptions, Client};
use std::error::Error;
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {

   // Load the MongoDB connection string:
   let client_uri = "mongodb://127.0.0.1:27017";

   // A Client is needed to connect to MongoDB:
   let mut options = ClientOptions::parse(&client_uri).await?;
   options.app_name = Some("testing".to_string());
   let client = Client::with_options(options)?;
   
   // get the collection here
   let items = client.database("my_database").collection("inventory");

   // aggregate options and pipeline
   let pipeline = vec![doc! {"$match": {"name": "FOO"}}];
   let options = AggregateOptions::builder().allow_disk_use(true).build();

   // I'm using tokio for async-await library
   let data = items
      .aggregate(pipeline, options)
      .await
      .map_err(|e| println!("{}", e));

    // data is a Result<mongodb::Cursor> type
    match data {
       Ok(cursor) => {
        
          // I want to iterate the returned documents here
          // this doesn't compiles
          while let Some(doc) = cursor.next().await {
              println!("{}", doc?)
          }
       },
       Err(e) => println!("{:?}", e),
}

上面的代码返回一个错误。它提示光标没有 next()内的功能。

 while let Some(doc) = cursor.next().await {
   |                          ^^^^ method not found in `mongodb::Cursor`

我在这里阅读了 mongodb::Cursor 的手册:https://docs.rs/mongodb/1.2.1/mongodb/struct.Cursor.html

这里是聚合函数https://docs.rs/mongodb/1.2.1/mongodb/struct.Collection.html#method.aggregate

如您所见,聚合方法应返回 Result<Cursor> .正如手册所述:

A cursor can be used like any other Stream. The simplest way is just to iterate over the documents it yields:

while let Some(doc) = cursor.next().await {
  println!("{}", doc?)
}

为什么它不起作用?

我在 Cargo.toml 中的依赖项:

[dependencies]
tokio = { version = "0.2", features = ["macros", "rt-threaded"]  }
serde = { version = "1.0", features = ["derive"] }
mongodb = "1.2.0"

如果我打印光标 println!("{:?}", cursor); .它包含其中的数据。如何从这个游标中取出数据?

最佳答案

我找到了!只需在文件顶部添加 use tokio::stream::StreamExt;,剩下的就可以了。

...all the other methods that an 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.

// main.rs
use mongodb::bson::{doc, Bson};
use mongodb::{options::AggregateOptions, options::ClientOptions, Client};
use std::error::Error;
use tokio;

// don't forget this!
use tokio::stream::StreamExt;

https://stackoverflow.com/questions/67014621/

相关文章:

python - 类型错误 : forward() takes 2 positional argum

ios - FaSTLane 设置 - 致命 : could not read Password f

c# - 使用 Newtonsoft.JSON 自定义转换器读取具有不同输入的 json

javascript - SwiftUI:在 macOS 上与 WKWebView 的 Javasc

android - 如何在 Android 中更改 TextInputLayout 的 boxStr

git - 如何使用 gitlab-ci.yml 进行简单的 pull ?

validation - VeeValidate 4 : two forms on one page

spring-boot - StreamingResponseBodyReturnValueHand

java - 在 Spring Cloud Gateway 中获取真实的客户端 IP 地址

javascript - 如何让 Bootstrap Toasts 不自动消失?