Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoengine - Embedded document filtering

I am working on Project model with Participants as embedded documents. Following is th structure in which it is stored.

{ "_id" : ObjectId( "5277a15c2d6d1302a2a9bf88" ),
  "code_certified" : true,
  "description" : "This is gonna to be accepted.",
  "owners" : [ 
    "5277a1472d6d1302a2a9bf86" ],
  "participants" : [ 
    { "id" : ObjectId( "5277a15c2d6d1302a2a9bf87" ),
      "invitee" : { "email" : "[email protected]",
        "name" : "P",
        "id" : "5277a1472d6d1302a2a9bf86" },
      "inviter" : { "email" : "[email protected]",
        "name" : "P",
        "id" : "5277a1472d6d1302a2a9bf86" },
      "role" : "owner",
      "date_invited" : Date( 1383523200000 ),
      "status" : "accepted" }, 
    { "id" : ObjectId( "5277a17f2d6d1302a2a9bf8d" ),
      "invitee" : { "id" : "5277a1282d6d1302a2a9bf85",
        "name" : "Pravin Mhatre",
        "email" : "[email protected]" },
      "inviter" : { "id" : "5277a1472d6d1302a2a9bf86",
        "email" : "[email protected]",
        "name" : "P M" },
      "role" : "contributor",
      "date_invited" : Date( 1383523200000 ),
      "status" : "pending" } ],
  "task_sequence" : 1,
  "title" : "Accept" }

I want to retrieve a list of Projects with accepted participation request (i.e. participants.status = "accepted").

I am trying with following code. But it returns all projects.

ApiResponse(Project.objects.filter(participants__invitee__id=str(request.user.id), participants__status__iexact="accepted").all(), ProjectEncoder).respond()
like image 824
Pravin Avatar asked Nov 04 '13 13:11

Pravin


1 Answers

Try using $elemMatch which is aliased to match in mongoengine:

Project.objects.filter(participants__match={"status":"accepted",
                                            "invitee.id":request.user})
like image 157
Ross Avatar answered Oct 22 '22 14:10

Ross