MongoDB 通过其他字段在嵌套数组中添加字段

MongoDB Add Field in nested array by other field

你好,我有简单的合集:

{
    _id: 1,
    books: [
         { bookId: 55, c: 5},
         { bookId: 66, c: 6},
         { bookId: 77, c: 7},
    ]
}

如何通过计算其他字段来添加新字段? 在这里,我通过计算字段“C”

将字段“Z”添加到嵌套数组中当前找到的对象
updateOne(
{ 
  _id : 1, 
  'books.bookId' : 66 
} ,
{
  [
      {    $addFields: { "books.$.z" : { "$sum" : ["$books.$.c", 1]  } }    }
  ]
}

预期结果:

{
    _id: 1,
    books: [
         { bookId: 55, c: 5},
         { bookId: 66, c: 6, z:7},
         { bookId: 77, c: 7},
    ]
}

我认为有一个简短的条目(可能使用新的 $getField ?!),我认为 mango 仍然可以结合 'position operator $' + ('varible operator reference by prefix $' or 'combine with $ getField') 我在样本中的尝试方式

使用aggregation pipeline in the update method to leverage the operators $map, $mergeObjects and $cond达到预期效果:

.updateOne(
    // The query will find docs where *at least* one bookId in the
    // books array equals 66 -- but remember it does not pinpoint
    // the location in the array!  We will tackle that in the update
    // pipeline to follow...
    { _id: 1, 'books.bookId': 66 },
    [
        { $set: {
            books: {
                $map: {
                    input: '$books',
                    in: {
                        $mergeObjects: [
                            '$$this',
                            {
                                $cond: [
                                    { $eq: ['$$this.bookId', 66] }, // IF books.bookId == 66
                                    { z: { $sum: ['$$this.c', 1] } }, // THEN merge a new field 'z' with calced value
                                    null  // ELSE merge null (a noop)
                                ]
                            }
                        ]
                    }
                }
            }
        } }    
    ]
)