0

I'm just starting with mongodb.

Is it possible to query the embedded array of "items" objects from below in an aggregate stage

[
    {
        "_id": ObjectId("5fdbea7c15e31a000858e345"),
        "orderno": "111",
        "items": [
            {
                "linenum": 1,
                "itemcode": "item1"
            },
            {
                "linenum": 2,
                "itemcode": "item2"
            },
            {
                "linenum": 3,
                "itemcode": "item3"
            }
        ]
    }
]

so it can be returned as a collection of objects?

[
    {
        "linenum": 1,
        "itemcode": "item1"
    },
    {
        "linenum": 2,
        "itemcode": "item2"
    },
    {
        "linenum": 3,
        "itemcode": "item3"
    }
]

Everything I tried so far always embed the array in a document like below

[
    {
        "items": [
            {
                "linenum": 1,
                "itemcode": "item1"
            },
            {
                "linenum": 2,
                "itemcode": "item2"
            },
            {
                "linenum": 3,
                "itemcode": "item3"
            }
        ]   
    }
]

thanks

1

1 Answer 1

1

Use $unwind to make each array element its own document, then $replaceRoot if desired to lift the array element to top level.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is exactly what I was looking

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.