I have a document like this
{
"_id" : ObjectId("6228cd8e72e74fa2a4bbd76c"),
"userId" : 8426,
"answer" : "https://cdn.upgrad.com/resumejyotiranjana.docx",
"updatedAt" : ISODate("2022-06-09T13:48:17.296Z"),
"questionIdentifier" : "resumeLink",
}
I need to convert answer into array of objects, The existing answer will become resumeLink properties and updatedAT will become dateUploaded in object.
{
"_id" : ObjectId("6228cd8e72e74fa2a4bbd76c"),
"userId" : 8426,
"answer" : [
{
"resumeLink":"https://cdn.upgrad.com/resume/asasjyotiranjana11.docx",
"dateUploaded": "2022-06-09T13:48:17.296Z",
"resumeId": "7fa1478d-478f-4869-9c4b-7ca8c0b9434g",
"source": "hiration"
}
],
"updatedAt" : ISODate("2022-06-09T13:48:17.296Z"),
"questionIdentifier" : "resumeLink",
}
Whats the quick way to achieve this with mongo query? thanks in advance
CodePudding user response:
Use aggregation query as below. You may need to add some fields in that.
const agg = [
{
'$match': {
'userId': 8426
}
}, {
'$group': {
'_id': '$userId',
'answers': {
'$addToSet': {
'recordId': '$_id',
'resumeLink': '$answer'
}
}
}
}
];
CodePudding user response:
Below mongo query worked:
db.getCollection('userfeedback').updateMany(
{userId:8426, questionIdentifier:"resumeLink"},
[{
"$set": {
answer: [{
"resumeLink": "$answer",
"resumeId": UUID().hex().match(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/).slice(1,6).join('-'),
"uploadSizeInByte": -1,
"source":"manual",
"dateUploaded": "$updatedAt"
}]
}
}]
)