I have a MongoDB collection containing documents like these:
{ "id": "62cd5de762c595905e37821b", "letterNo": "122233", "letterDate": "2023-03-01", "metaData": { "name": "test", "family ": "test" } }, { "id": "62cd5de762c595905e37821a", "letterNo": "122233", "letterDate": "2023-03-01", "metaData": { "type": "xxxx", "where": "test" } }
I want to $group in metaData field as metaData_string, that every shema change to string live this:
{ "id": "62cd5de762c595905e37821a", "letterNo": "122233", "letterDate": "1400-03-01", "metaData_string":"{n'name': 'test',n'family ': 'test'n}" }, { "id": "62cd5de762c595905e37821a", "letterNo": "122233", "letterDate": "1400-03-01", "metaData_string":"{n'type': 'xxxxx',n'where': 'test'n}" }
Is it possible using the Aggregation Framework only? I haven’t seen reference to subdocuments in the aggregation framework documentation, so I think it’s not…
Thx you all.
2
Answers
You can use
$function
, if it’s a one-time operation, but you’ll need to enable server-side javascript. Like this:Playground link.
Regarding the above answer due to security vulnerability such as JS injection I recommend using
$map, $reduce
operator to get the string result and concat them together, below is the solution I come up with that also handles the nested list of objects:Playground_Link