odmantic icon indicating copy to clipboard operation
odmantic copied to clipboard

Array query operators

Open art049 opened this issue 3 years ago • 3 comments

Suggested implementation of $elemMatch $all and $size

MongoDB Reference

Example model:

class Thing(Model):
    array: List[int]

$elemMatch

Array containing the number 42 at least once:

Thing.array.any().eq(42)
eq(Thing.array.any(), 42)
Thing.array.any() == 42
42 in Thing.array # if possible using __contains__

$elemMatch

Array containing only elements greater than 12:

Thing.array.all().gt(42)
gt(Thing.array.all(), 42)
Thing.array.all() > 42

$size

Array containing more than 3 elements:

Thing.array.size().gte(3)
gte(Thing.array.size(), 3)
Thing.array.size() >= 3
len(Thing.array) >= 3 # if possible

art049 avatar Oct 26 '20 10:10 art049

When will be the next release? I would love to have this feature.

But I really need sequences over EmbeddedModels, and I don't know if I should open a new issue (or there is already one) e.g.:

class EmbeddedAuthor(EmbeddedModel):
    name: str
    year: int

class Book(Model):
    title: str
    authors: List[EmbeddedAuthor]

The query could be something like:

Book.authors.any(EmbeddedAuthor.name == "Frederick Forsyth")

but I would love much more:

Book.authors.any().name == "Frederick Forsyth"

Looking about what MongoDB allows to do, it seems that we can query over arrays with the "any" operator transparently, i.e.:

Thing.array.any() == 42

and

Thing.array == 42

would be the same. This is especially interesting for embedded models:

Book.authors.name == "Frederick Forsyth"

which should read like "Tell me which books have at least one author with name "Frederick Forsyth".

Thanks again for this great piece of software.

erny avatar Jan 26 '21 08:01 erny

Hey @erny. Thanks for your enthusiasm :smile: . I'm currently working on this feature, release should come soon :wink:

I totally agree with the use case you described and it should definitely possible to have it with this feature !

art049 avatar Mar 15 '21 18:03 art049