topnotch228
topnotch228

Reputation: 93

Retrieve an embedded array and return as a collection of object in mongodb

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

Upvotes: 0

Views: 116

Answers (1)

D. SM
D. SM

Reputation: 14520

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

Upvotes: 1

Related Questions