Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to run aggregations? #73

Open
8176135 opened this issue Feb 19, 2021 · 3 comments
Open

How to run aggregations? #73

8176135 opened this issue Feb 19, 2021 · 3 comments

Comments

@8176135
Copy link

8176135 commented Feb 19, 2021

What is the intended method to run an aggregation query with wither?

Currently I am doing something like this:

let path_regex = wither::bson::Regex { pattern: format!("{}.*", path), options: String::new() };
let pipeline = vec!
    [
        doc!{
            "$match": {
                "path": path_regex
            }
        },
        doc!{
            "$sample": {
                "size": 1
            }
        }
    ];

let mut cursor: Cursor<_> = DataBlockMongo::collection(&db).aggregate(pipeline, AggregateOptions::default()).await.unwrap();

if let Some(chosen_item) = cursor.next().await {
    let chosen_item = DataBlockMongo::instance_from_document(chosen_item.unwrap()).unwrap();
}

Which works, but requires converting to and from a document.

Is this the intended method?
If so, I can't seem to find this documented anywhere.

@thedodd
Copy link
Owner

thedodd commented Feb 22, 2021

@8176135 currently that is the only way to do so, and that is part of the reason I decided to expose the instance_from_document method on Model impls.

I think it shouldn't be a heavy lift at all to encapsulate this behavior that you've shown above. Technically there are plenty of things which a user can do to cause the output of an agg pipeline to break serialization ... so perhaps we introduce a new Model::aggregate method, and then simply include in the docs that the output is expected to be able to deserialize as model instances.

If the output is not intended to deserialize as model instances, then perhaps we recommend using the collection's aggregate method. What do you think?

@simoneromano96
Copy link
Collaborator

I am particularily interested in the $lookup operator since I have some simple relations that currently I handle with the instance_from_document.

@27justin
Copy link

Is this still planned?
I have a version of wither sitting on my fork right now that supports Model::aggregate.
My fork, however, requires mongodb version 2.21.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants