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?

1
  • What is not working with $slice as explained in the documentation? Commented Sep 2, 2016 at 9:34

1 Answer 1

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"
            }
        }
    } 
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.