How can I get the value of a specific field in the document? was

I’m trying to get the value of a specific field in the document when searching for it like:

use mongodb::{bson::{doc,Document},options::ClientOptions, Client};
//..
let client = Client::with_options(ClientOptions::parse("mongodb+srv://user:pass@cluster0.um0c2p7.mongodb.net/?retryWrites=true&w=majority").await.unwrap()).unwrap();
let coll = client.database("braq").collection("users");
let user  = coll.find_one(doc!{"user":"user1"},None).await.unwrap();
println!("Hello, {}!",user.user1);

The error I get:

#9 311.1 error[E0698]: type inside `async fn` body must be known in this context
#9 311.1   --> src/main.rs:46:35
#9 311.1 46 |     let db = client.database("braq").collection("users");
#9 311.1    |                                      ^^^^^^^^^^ cannot infer type for type parameter `T` declared on the associated function `collection`
#9 311.1 note: the type is part of the `async fn` body because of this `await`
#9 311.1   --> src/main.rs:47:50
#9 311.1 47 |     let deb  = db.find_one(doc!{"user":"user1"},None).await.unwrap();
#9 311.1    |                                                     ^^^^^^
#9 311.1 
------
 > [4/4] RUN cargo install --path .:
#9 311.1 46 |     let db = client.database("braq").collection("users");
#9 311.1    |                                      ^^^^^^^^^^ cannot infer type for type parameter `T` declared on the associated function `collection`
#9 311.1 note: the type is part of the `async fn` body because of this `await`
#9 311.1   --> src/main.rs:47:50
#9 311.1 47 |     let deb  = db.find_one(doc{"user":"user1"},None).await.unwrap();
#9 311.1    |                                                     ^^^^^^

How can I do that without errors?

You have to set type, something like this

let coll = client.database("braq").collection::<User>("users");

Just to expand on Marko’s answer a bit - collection requires a type parameter so it knows how to dezerialize the data. You can use the bson Document type if you don’t know the shape of the data or don’t want to use specific structs:

let coll = client.database("braq").collection::<Document>("users");

otherwise you can define a struct that corresponds to the shape of the data you’re retrieving:

#[derive(Deserialize)]
struct User {
  name: String,
  age: i32,
}
//..
let coll = client.database("braq").collection::<User>("users");

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.