Home > Net >  Rust Mongodb find and filter specific data
Rust Mongodb find and filter specific data

Time:07-29

How can I do the mongosh shell equivalent in the Rust MongoDB driver?

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

That returns all the books from the queried author? (Show the book field only by "George Orwell")

The doc shows one example with the filter but I can't replicate the above with both criteria. FindOptions didn't seem to have anything that could be used for it.

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?;

I guess the command above would be similar to the following in the mongosh shell:

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

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

CodePudding user response:

Looking at the documentation for the FindOptions struct, there is a projection field. The FindOptionsBuilder has a method projection that can set this field.

This leads me to believe you can do the following:

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?;
  • Related