简体   繁体   中英

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" : "pravin@gmail.com",
        "name" : "P",
        "id" : "5277a1472d6d1302a2a9bf86" },
      "inviter" : { "email" : "pravin@gmail.com",
        "name" : "P",
        "id" : "5277a1472d6d1302a2a9bf86" },
      "role" : "owner",
      "date_invited" : Date( 1383523200000 ),
      "status" : "accepted" }, 
    { "id" : ObjectId( "5277a17f2d6d1302a2a9bf8d" ),
      "invitee" : { "id" : "5277a1282d6d1302a2a9bf85",
        "name" : "Pravin Mhatre",
        "email" : "pravinhmhatre@gmail.com" },
      "inviter" : { "id" : "5277a1472d6d1302a2a9bf86",
        "email" : "pravin@gmail.com",
        "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 (ie 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()

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

Project.objects.filter(participants__match={"status":"accepted",
                                            "invitee.id":request.user})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM