简体   繁体   中英

Custom MongoDB query to return specific sub-documents

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!

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"
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM