Home > Mobile >  MongoDB Add Field in nested array by other field
MongoDB Add Field in nested array by other field

Time:02-26

Hello i have simple collection:

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

How i can add new field by calulate other field? here i add field “Z” to current found object in nested array by it calculate field “C”

updateOne(
{ 
  _id : 1, 
  'books.bookId' : 66 
} ,
{
  [
      {    $addFields: { "books.$.z" : { "$sum" : ["$books.$.c", 1]  } }    }
  ]
}

Expected result:

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

I think there is a short entry (possibly using new $getField ?!), I think mango is still able to combine ‘position operator $’ (‘varible operator reference by prefix $’ or ‘combine with $getField’) how i try in my sample

CodePudding user response:

Use the aggregation pipeline in the update method to leverage the operators $map, $mergeObjects and $cond to achieve the desired results:

.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)
                                ]
                            }
                        ]
                    }
                }
            }
        } }    
    ]
)
  • Related