Add multiple values using $addToSet Mongo operator

后端 未结 2 569
情深已故
情深已故 2021-02-03 23:05

$addToSet operator adds a value to an array only if the value is not already in the array. If the value is in the array, $addToSet does not modify the array.

相关标签:
2条回答
  • 2021-02-03 23:13

    From the docs for $addToSet:

    If the value is an array, $addToSet appends the whole array as a single element. To add each element of the value separately, use $addToSet with the $each modifier. See Modifiers for details.

    So you should use this instead:

    db.c.update({}, {$addToSet: {a: {$each: [2, 4]}}})
    
    0 讨论(0)
  • 2021-02-03 23:30

    Yep. But you need the $each modifier to be added in your statement:

    db.c.update({},{ $addToSet: { a: {$each: [ 2, 4 ] } } })
    

    And the result:

    { "a" : [ 1, 2, 3, 4 ] }
    
    0 讨论(0)
提交回复
热议问题