1

I have a processes document with a nested attachments array, I want to return get the fileName with the processes _id and attachment _id.

enter image description here

I have tried many options, my latest attempt still return all items from the attachments array. I only want the attachment that matches the attachment id past in.

db.getCollection('processes').find(
{$and: [ { "_id" : ObjectId("5a9455d7854cd987a40b1ba4") }, 
{ "attachments._id" : ObjectId("5a983da6201ba5a2302fb38f") }]},
{'attachments._id': 1, 'attachments.fileName': 1}
)

Any suggestion is greatly appreciated, thanks!

1 Answer 1

3

You can use $elemMatch in projection to get only one filtered subdocument from nested array:

db.getCollection('processes').find(
    { "_id" : ObjectId("5a9455d7854cd987a40b1ba4") },
    { attachments: { $elemMatch: { _id: ObjectId("5a983da6201ba5a2302fb38f") } } } )
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks Mickl!, That works exactly how I wanted to.

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.