Skip to content
This repository was archived by the owner on Oct 18, 2021. It is now read-only.
This repository was archived by the owner on Oct 18, 2021. It is now read-only.

[Ask]: using $in doc! #298

@deltavin

Description

@deltavin

I am trying to use $in to find documents. In the following example, I'm trying to get documents where category is either "news" or "politics".

Attempt 1: fails
using a vector of categories:

let cats: Vec<&str> = vec!["news", "politics"];
let cursor = collection.find(Some(doc! {"categories": {"$in": cats}}),None,);

This fails to compile, saying: the trait bound mongodb::Bson: std::convert::From<std::vec::Vec<&str>> is not satisfied

Attempt 2: fails
Instead of a vector, use an array:

let cats = ["news", "politics"];
let cursor = collection.find(Some(doc! {"categories": {"$in": cats}}),None,);

This also fails to compile saying: the trait bound mongodb::Bson: std::convert::From<[&str; 2]> is not satisfied

Attempt 3: passes
hard-code the array in the query:

let cursor = collection.find(Some(doc! {"categories": {"$in":  ["news", "politics"]}}),None,);

This works

Question
What is the right way to use $in or any such operator that expects a collection of strings. Thanks

Edit:
Based on the error message, here's what I ended up doing to make it work:

let cats: Vec<Bson> = some_str.split(",").collect::<Vec<&str>>().into_iter().map(|i| Bson::from(i)).collect();
let cursor = collection.find(Some(doc! {"categories": {"$in": cats}}),None,);

Let me know if there's a better way around this, otherwise, you may close/remove the post.
thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions