【问题标题】:How to find and select fields in the Rust MongoDB driver?Rust Mongodb 查找和过滤特定数据
【发布时间】:2022-07-29 10:03:15
【问题描述】:

如何在 Rust MongoDB 驱动程序中执行 mongosh shell 等效?

db.library.find({"author": "George Orwell"}, {book: 1, _id:0})

返回查询作者的所有书籍? (仅显示“乔治·奥威尔”的书籍字段)

该文档显示了一个带有过滤器的示例,但我无法使用这两个条件复制上述内容。 FindOptions 似乎没有任何可用的东西。

use mongodb::{bson::doc, options::FindOptions};

// Query the books in the collection with a filter and an option.
let filter = doc! { "author": "George Orwell" };
let find_options = FindOptions::builder().sort(doc! { "title": 1 }).build();
let mut cursor = typed_collection.find(filter, find_options).await?;

我猜上面的命令会类似于 mongosh shell 中的以下命令:

db.library.find({"author": "George Orwell"}).sort({book: 1})

https://docs.rs/mongodb/latest/mongodb/

【问题讨论】:

    标签: mongodb rust find crud


    【解决方案1】:

    查看documentation for the FindOptions struct,有一个projection fieldFindOptionsBuilder 有一个方法projection 可以设置这个字段。

    这让我相信你可以做到以下几点:

    use mongodb::{bson::doc, options::FindOptions};
    
    // Query the books in the collection with a filter and an option.
    let filter = doc! { "author": "George Orwell" };
    let find_options = FindOptions::builder().projection(doc! { "book": 1, "_id": 0 }).build();
    let mut cursor = typed_collection.find(filter, find_options).await?;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2021-09-20
      • 2021-07-26
      • 2017-12-15
      • 2019-05-17
      • 2022-11-30
      • 1970-01-01
      相关资源
      最近更新 更多