'MongoDB - How to return only the items from an array

Data-Structure's Format:

[
  {
    "related": [
      {
        "_id": "xxvxcv",
        "price": "5266",
        "title": "Title 1"
      },
      {
        "_id": "fggfd",
        "price": "5266",
        "title": "Title 2"
      }
    ]
  }
]

Now, I want to return only the object from the related array.

I want to remove the related key and return only the items present in the related array.

Expected output should be like this:

[ 
    {
        "_id": "xxvxcv",
        "price": "5266",
        "title": "Title 1"
      },
      {
        "_id": "fggfd",
        "price": "5266",
        "title": "Title 2"
    }
]

What's my aggregation query should be? Any suggestions?

db.collection.aggregate([  ..??  ])


Solution 1:[1]

$unwind: Deconstructs an array field from the input documents to output a document for each element.

$replaceRoot: Replaces the input document with the specified document.

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

Output

[
  {
    "_id": "xxvxcv",
    "price": "5266",
    "title": "Title 1"
  },
  {
    "_id": "fggfd",
    "price": "5266",
    "title": "Title 2"
  }
]

Sample Mongo Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun