1

I am trying to convert a mongoDB documents object into an array with the same data. I have a document structured like this:

{
    _id:"43434",
    fistname: 'Bob',
    lastname: 'Toto',
    address: { city: "cityName", postalCode: "000000", streetName: "streetname" },
}

And I want to restructure my data like this :

{
    _id:"43434",
    fistname: 'Bob',
    lastname: 'Toto',
    address: [{ city: "cityName", postalCode: "000000", streetName: "streetname" }],
}

How would I go about achieving that? Can I use the $project (aggregation) of mongo?

1
  • If you wanted to write results back to collection then aggregate won't help you -unless if you're on version <4.2. prior versions has $out but I wouldn't prefer as it's destructive coz it will overwrite collection with new data, You might see address converted to array with value as null (this happens if you don't have address in first place) !! Please check the above link it should help you or if you're in v4.2 use $merge in aggregation !! Commented Oct 23, 2019 at 15:07

1 Answer 1

1

Try this query

db.tester.aggregate(
   [
       {$match:{"_id":ObjectId("5db06342f079fa02a63adaf8")}},
      {
         $project: {
            fistname: 1,
            lastname:1,
            address: [{ city:'$address.city','postalCode':'$address.postalCode',streetName:'$address.streetName'}]
         }
      }
   ]
)
Sign up to request clarification or add additional context in comments.

1 Comment

Please try this query

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.