Vishal Sharma
Vishal Sharma

Reputation: 129

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([  ..??  ])

Upvotes: 0

Views: 1436

Answers (1)

Yong Shun
Yong Shun

Reputation: 51450

$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

Upvotes: 4

Related Questions