1
votes

Not really used with advanced mongo features, so I'm looking to find out the proper way to return specific fields from my collection. Given the following structure:

[
    {
        _id: 1,
        comments: [
            {
                owner: "aaa",
                feedback: { userText: 'nice', thumb: 'up'}
            },
            {
                owner: "aab",
                feedback: { userText: 'not nice', thumb: 'down'}
            }
        ]
    },
    {
        _id: 2,
        comments: [
            {
                owner: "aac",
                feedback: { userText: 'nice', thumb: 'up'}
            }
        ]
    },
    {
        _id: 3,
        comments: [
            {
                owner: "aad",
                feedback: { userText: 'not nice', thumb: 'down'}
            },
            {
                owner: "aaa",
                feedback: { userText: 'nice', thumb: 'up'}
            }
        ]
    }
]

I'm trying the obtain all the feedbacks the belongs to the owner with the id "aaa". The output should look like this:

[

    {
        owner: "aaa",
        feedback: { userText: 'nice', thumb: 'up'}
    },
    {
        owner: "aaa",
        feedback: { userText: 'nice', thumb: 'up'}
    }

]

What I've done so far is to use $elemMatch on the `comments' field with the specific owner id. This will return me all the documents from the collection, but still need to iterate through all of them which I'm not that sure how fast will be since the collection will grow pretty fast..

Thanks!

1

1 Answers

1
votes

You can use below aggregation

db.collection.aggregate([
  { "$match": { "comments.owner": "aaa" }},
  { "$unwind": "$comments" },
  { "$match": { "comments.owner": "aaa" }},
  { "$replaceRoot": { "newRoot": "$comments" }}
])

Output

[
  {
    "feedback": { "thumb": "up", "userText": "nice" },
    "owner": "aaa"
  },
  {
    "feedback": { "thumb": "up", "userText": "nice" },
    "owner": "aaa"
  }
]