[SERVER-9591] Update: $push + $unique Created: 06/May/13  Updated: 06/Dec/22  Resolved: 29/Jun/19

Status: Closed
Project: Core Server
Component/s: Write Ops
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Scott Hernandez (Inactive) Assignee: Backlog - Query Team (Inactive)
Resolution: Won't Do Votes: 4
Labels: push, unique
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to SERVER-2362 Add new Deque/Set operation modifiers Closed
is related to SERVER-11210 $addToSet missing $position and $slic... Closed
Assigned Teams:
Query
Participants:

 Description   

Allow new $unique option for $push to allow better control over array/set semantics.

db.c.save({_id:1, a: [{name:"scott"}, {name:"john"}]});
db.c.update({_id:1}, {$push: {a : {$each:[{name:"scott"}], $unique:"name"}}}) // no-op



 Comments   
Comment by Asya Kamsky [ 29/Jun/19 ]

SERVER-40381 implemented support for aggregation expressions to specify update for 4.2. 

You can see some examples here.

This can be done by setting the array to its old value if the name already exists, or $concatArrays if it does not.

The more complex "upsert to array" that was mentioned:

db.c.update({}, [
      {$set:{array:{$cond:{
            if: {$in:[ "Scott" ,  "$array.name"]},
            then:"$array" ,   // process array making appropriate change to correct element
            else: {$concatArrays: [ "$array", [ {name: "Scott"}] ]}
      }}}}
]);

Generated at Thu Feb 08 03:20:53 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.