0

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.

2 Answers 2

1

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.

1
  • Hi Afil, thanks a lot for you quick answer! I would like to do it preferably through MongoEngine. If I couldn't get it done, it's great to remember that I can make a MongoDB call at MongoEngine and use $elemMatch. Very best regards! Aug 23, 2014 at 5:46
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.