Emanuel Vianna
Emanuel Vianna

Reputation: 161

Query with multiple conditions on a nested entry in MongoEngine

I have a Document A that contains a ListField b of a particular type EmbeddedDocument B, which have two StringFields x and y.

class B(EmbeddedDocument):
    x = StringField()
    y = StringField()

class A(Document):
    b = ListField(EmbeddedDocumentField(B))

Let's populate them first:

b1 = B(x="x1", y="y1")
b2 = B(x="x2", y="y2")
a = A(b=[b1, b2])
a.save()

I want to search for an instance of A that contains a particular entry B with values x=x1 and y=y1.

I tried to build a query with two contains, one for each value.

A.objects(b__x__contains="x1", b__y__contains="y1")
[<A: A object>]

The success case works. The problem is that the conditions are independent, then they can match different entries of list b:

A.objects(b__x__contains="x1", b__y__contains="y2")
[<A: A object>]

Is there a way, in MongoEngine, to ensure that these two conditions will be applied in the same entry?

Thanks in advance.

Upvotes: 0

Views: 1275

Answers (2)

Emanuel Vianna
Emanuel Vianna

Reputation: 161

I found the answer in an issue #379 at MongoEngine Github.

$elemMatch was mapped to field__match.

So the success case works:

A.objects(b__match={"x": "x1", "y": "y1"})
[<A: A object>]

And wrong case one fail:

A.objects(b__match={"x": "x2", "y": "y1"})
[]

Thanks a lot Afil to show me that what I need was equivalent to $elemMatch.

Upvotes: 0

Newbie
Newbie

Reputation: 1531

As of I understand your question. You could try $elemMatch

Eg: Find Query

db.A.findOne(
   {
     b : {$elemMatch : {"x":"x1", "y":"y1"}}
   }
);

Hope this will help you.

Upvotes: 1

Related Questions