我正在尝试查找和更新嵌套对象数组中的某些字段。我正在用$unwind
展平数组,然后使用$match
隔离要更新的实例,但是$set
似乎不起作用。也许我不能以这种方式使用它?
尝试$set
之前的两个条目:
[
{
_id: 5dabcdf7501b3b4ab66f9f76,
tasks: {
_id: 5dabcde5c4a0ab4aa106af7d,
task: '19',
name: 'beyond',
dimension: 'Transformational Leadership',
subDimension: 'unknown',
points: 1,
imgUrl: 'imgs/19.svg',
text: 'You completed a custom challenge!',
userId: '5dabcdf7501b3b4ab66f9f76',
createdAt: '48-Mo:01:48'
},
awards: [],
firstName: 'bob',
lastName: 'bob',
location: 'Campbell, USA',
unit: 'AMSBG',
group: 3,
team: 1,
createdAt: 2019-10-20T03:01:11.071Z,
updatedAt: 2019-10-29T16:03:54.002Z,
no_of_tasks: 9,
points: 9
},
{
_id: 5dabcdf7501b3b4ab66f9f7d,
tasks: {
_id: 5dabcde5c4a0ab4aa106af7d,
task: '19',
name: 'beyond',
dimension: 'Transformational Leadership',
subDimension: 'unknown',
points: 1,
imgUrl: 'imgs/19.svg',
text: 'You completed a custom challenge!',
userId: '5dabcdf7501b3b4ab66f9f7d',
createdAt: '48-Mo:01:48'
},
awards: [],
firstName: 'bobette',
lastName: 'bob',
location: 'Taiperi',
unit: 'Finance',
group: 1,
team: 1,
createdAt: 2019-10-20T03:01:11.072Z,
updatedAt: 2019-10-29T18:24:20.480Z,
no_of_tasks: 40,
points: 40
}
]
我认为应该工作的查询:
const tasks = await User.aggregate([
{ $unwind: '$tasks' },
{ $match: {'tasks.name': foo.name} },
{ $set:
{'tasks.text': foo.text,
'tasks.subDimension': foo.subDimension }
}
])
希望了解为什么它会失败