1

I have a collection with documents like below,

Document1:

{
    name: "tester1",
    reports: [{
            name: "report1",
            type: "overflow"
        },
        {
            name: "report2",
            type: "invalid form"
        }
    ]
}

Document2:

{
    name: "tester2",
    reports: [{
            name: "report3",
            type: "crossed"
        },
        {
            name: "report4",
            type: "unknown issue"
        }
    ]
} 

Document3:
{
    name: "tester3",
    reports: [{
            name: "report4",
            type: "try again"
        },
        {
            name: "report6",
            type: "invalid data"
        }
    ]
}

I am trying to implement query to fetch data like,

[{
        name: "report1",
        type: "overflow"
    },
    {
        name: "report2",
        type: "invalid form"
    },
    {
        name: "report3",
        type: "crossed"
    },
    {
        name: "report4",
        type: "unknown issue"
    },
    {
        name: "report4",
        type: "try again"
    },
    {
        name: "report6",
        type: "invalid data"
    }
]

I tried using grouping and projecting but unable to generate this output.

I need only inner arrays as final documents so that I can apply aggregation queries to achieve pagination and search.

3
  • Each document contains above array? I am trying to understand your document Commented Jul 23, 2020 at 11:10
  • No, I have added three documents with data Commented Jul 23, 2020 at 11:13
  • What kind of "search" you need to do? Commented Jul 23, 2020 at 12:22

1 Answer 1

1

You can use $unwind along with $replaceRoot in order to promote reports to the root level and then you can use $skip or $limit:

db.collection.aggregate([
    { $unwind: "$reports" },
    { $replaceRoot: { newRoot: "$reports" } },
    { $limit: 5 }
])

Mongo Playground

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.