Hello there! I have some schemas set up like this:
{ user: '123', code: 'abc', uses: [...] },
{ user: '123', code: 'def', uses: [...] },
and my goal is to transform them into this format:
{ user: '123', code: ['abc', 'def'], uses: [...] },
I've been experimenting with the following query:
schema.aggregate([
{ $unwind: '$uses' },
{ $group: { _id: '$_id', user: { $first: '$user' }, code: { $addToSet: '$code' }, uses: { $addToSet: '$uses' } } }
]);
However, I'm not getting the desired result. While the 'code' field has become an array, it only contains one code.
I recently updated a function and now need 'code' to be an array instead of a single value. With over 400 documents, I want to update them all to fit the new function without manual intervention.
UPDATE: After making some adjustments, it seems to be working with:
{ $unwind: '$uses' },
{ $group: { _id: '$user', code: { $addToSet: '$code' }, uses: { $addToSet: '$uses' } } }
The issue (I believe) was with user: { $first: '$user' }
, as removing it led to the expected outcome. Now the challenge is figuring out how to replace the old schemas with the updated ones.