Mongodb using redact with $eq and $arrayElemAt for the inner document array -


my documents structured this:

{     "_id" : objectid("57c93af8bf501124df658a0e"),     "friends" : [         {   "userid" : 14, "xxxx" : "xxx"   },         {   "userid" : 13,  "xxx" : "xxx"   }     ] },{     "_id" : objectid("57c93af8bf501124df658a0e"),     "friends" : [         {   "userid" : 1, "xxxx" : "xxx"    },         {   "userid" : 14,  "xxx" : "xxx"   }     ] } 

i need retrieve document has userid 14 in last element of friends array. desired output below:

{     "_id" : objectid("57c93af8bf501124df658a0e"),     "friends" : [         {   "userid" : 14,  "xxx" : "xxx"   }     ] } 

i tried use $slice operator last element of array in mongodb recommended; need on sub-documents.

how can structure query "friends.user" $eq 14 inside $redact using "$arrayelemat" @ -1?

run following aggregation pipeline desired result:

db.collection.aggregate([     { "$match": { "friends.userid": 14 } },     {         "$redact": {             "$cond": {                 "if": { "$eq": [{ "$arrayelemat": [ "$friends.userid", -1 ] }, 14 ] },                 "then": "$$keep",                 "else": "$$prune"             }         }     }  ]) 

Comments