MongoDB
 sql >> Cơ Sở Dữ Liệu >  >> NoSQL >> MongoDB

Làm cách nào để lấy bộ sưu tập tài liệu từ con trỏ mongodb?

Một con trỏ Cursor triển khai Stream từ futures thùng . Điều này được đề cập trong tài liệu :

Tôi thực sự khuyên bạn nên sử dụng try_collect() từ TryStreamExt đặc điểm để nhận Result<Vec<Document>> thay vì. Sau đó, bạn có thể sử dụng unwrap_or_else() để trả lại danh sách. Bạn cũng nên sử dụng collection_with_type() phương pháp lấy bộ sưu tập để kết quả của bạn sẽ được tự động giải mã hóa thành loại thích hợp thay vì chỉ Document (chỉ cần đảm bảo rằng nó triển khai Debug , SerializeDeserialize ).

Đây là một mẫu hoạt động

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![])
}



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. ORM có thừa với API NoSQL không?

  2. Làm cách nào để sử dụng toán tử 'Không thích' trong MongoDB

  3. MongoDB Spark Connector py4j.protocol.Py4JJavaError:Đã xảy ra lỗi khi gọi o50.load

  4. Trường nước ngoài của $ lookup có thể là trường tài liệu lồng nhau?

  5. ánh xạ trường id mongodb dữ liệu mùa xuân