0

My documents are structured like 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 to retrieve the document which has the userid as 14 in the last element of the friends array. The desired output is as below:

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

I tried to use the $slice operator to get last element of array in mongodb as recommended; but I need to do this on the sub-documents.

How can I structure the query for "friends.user" $eq to 14 inside the $redact using the "$arrayElemAt" at -1?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Soorya Prakash
  • 921
  • 3
  • 9
  • 29
  • What is not working with `$slice` as explained in the [documentation](https://docs.mongodb.com/manual/reference/operator/aggregation/slice/)? – dgiugg Sep 02 '16 at 09:34

1 Answers1

2

Run the following aggregation pipeline to get the desired result:

db.collection.aggregate([
    { "$match": { "friends.userid": 14 } },
    { 
       "$redact": {
            "$cond": {
                "if": { "$eq": [{ "$arrayElemAt": [ "$friends.userid", -1 ] }, 14 ] },
                "then": "$$KEEP",
                "else": "$$PRUNE"
            }
        }
    } 
])
chridam
  • 100,957
  • 23
  • 236
  • 235