Reply head informations and add extract array to same result

45 views Asked by At

someone colud please help me with this situation?

I have this fake JSON...

[
  {
    "user": {
      "type": "PF",
      "code": 12345,
      "Name": "Darth Vader",
      "currency": "BRL",
      "status": "SINGLE",
      "localization": "NABOO",
      "createDate": 1627990848665,
      "olderAdress": [
        {
          "localization": "DEATH STAR",
          "createDate": 1627990848775
        },
        {
          "localization": "TATOOINE",
          "createDate": 1627990555888
        },
        
      ]
    }
  }
]

My idea is, i need to extract the "olderAdress" and create new register but I need to keep the original register too. Example: This is the result I hope.

[
  {
    "_id": ObjectId("5a3456e000102030405000000"),
    "user": {
      "Name": "Darth Vader",
      "code": 12345,
      "createDate":1627990848665,
      "currency": "BRL",
      "localization": "NABOO",
      "status": "SINGLE",
      "type": "PF"
    }
  },  
  {
    "_id": ObjectId("5a789e000102030405000000"),
    "user": {
      "Name": "Darth Vader",
      "code": 12345,
      "createDate": 1627990848775,
      "currency": "BRL",
      "localization": "DEATH STAR",
      "status": "SINGLE",
      "type": "PF"
    }
  },
  {
    "_id": ObjectId("5a991e000102030405000000"),
    "user": {
      "Name": "Darth Vader",
      "code": 12345,
      "createDate": 1627990555888,
      "currency": "BRL",
      "localization": "TATOOINE",
      "status": "SINGLE",
      "type": "PF"
    }
  }
]

I try same think in this link (Test to extract values) to tests but unfortunately I cant. Somewoone could please help me?

1

There are 1 answers

2
Tom Slabbaert On BEST ANSWER

You're very close, what you want to do is just to add the new location to the array before $unwinding it.

like so:

db.collection.aggregate([
  {
    "$addFields": {
      "user.olderAdress": {
        "$concatArrays": [
          "$user.olderAdress",
          [
            {
              "localization": "NABOO",
              "createDate": "$$NOW"
            }
          ]
        ]
      }
    }
  },
   ... rest of pipeline ...
])

Mongo Playground