Extract value of array and add in the same select mongoDB

Viewed 119

I am new to the mongoDB aggregation and I have this situation. I have this Json and I need to convert by "select" this object:

{
    "type": "PF",
    "code": 12345
    "Name": Darth Vader,
    "currency": "BRL",
    "status": "SINGLE",
    "adress": [
        {
            "localization": "DEATH STAR",
            "createDate": 1627990848665
        },
        {
            "localization": "TATOOINE",
            "createDate": 1627990555665
        },
    ]
}

this way:

{
    "type": "PF",
    "code": 12345
    "Name": Darth Vader,
    "currency": "BRL",
    "status": "SINGLE",
    "localization": "DEATH STAR",
    "createDate": 1627990848665
},
{
    "type": "PF",
    "code": 12345
    "Name": Darth Vader,
    "currency": "BRL",
    "status": "SINGLE",
    "localization": "TATOOINE",
    "createDate": 1627990555665
}

So, after my query is complete, I will have 02 objects instead of 01. How can I do this? I would like to do this via select because after converting I will sort by createDate and limit the number of records to return to the API. I'm using Criteria em my project.

1 Answers

The way to do this is $unwind, this will make 1 copy of the document, for each member of the array.

Test code here

db.collection.aggregate([
  {
    "$unwind": {
      "path": "$user.adress"
    }
  },
  {
    "$set": {
      "user": {
        "$mergeObjects": [
          "$user",
          "$user.adress"
        ]
      }
    }
  },
  {
    "$unset": [
      "user.adress"
    ]
  },
  {
    "$sort": {
      "createDate": 1
    }
  },
  {
    "$limit": 10
  }
])

Edit1 (the above is if user is a field, if it was the name of the collection)

  • $$ROOT is a system variable that has as value all the document

Test code here

Query

db.collection.aggregate([
  {
    "$unwind": {
      "path": "$adress"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          "$adress"
        ]
      }
    }
  },
  {
    "$unset": [
      "adress"
    ]
  },
  {
    "$sort": {
      "createDate": 1
    }
  },
  {
    "$limit": 10
  }
])
Related