Home > front end >  Mongodb - How to return only the items from an Array?
Mongodb - How to return only the items from an Array?

Time:09-21

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 Obj from the related array.

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

Expected Output should be like this:

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

What's my aggregation should be? Any Sugggestions

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

CodePudding user response:

$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

  • Related