[SERVER-4708] "{ $pull : { field : _value } }" support removes the first occurrences of value from field, if field is an array. Created: 18/Jan/12  Updated: 06/Dec/22  Resolved: 13/Aug/17

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

Type: New Feature Priority: Major - P3
Reporter: gavinliu Assignee: Backlog - Query Team (Inactive)
Resolution: Duplicate Votes: 0
Labels: update
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

platform: redhat 6.1. mongodb version: 2.0.2


Issue Links:
Duplicate
duplicates SERVER-1014 A modifier to delete a single value f... Closed
Assigned Teams:
Query
Backwards Compatibility: Fully Compatible
Participants:

 Description   

{ $pull :

{ field : _value }

} will removes all occurrences of value from field, if field is an array.
In my project, I need { $pull :

{ field : _value }

} removes the first occurrences of value from field.
For example:
document:

{ "_id":"123", "boys":[ {"name":"jhon"}

,

{"name":"jhon"}

,

{"name":"gavin"}

]
}
As you see, the array "boys" has three elements, and the first is same
to the second. If I do {$pull:{"name":"jhon"}}, then the first and second element will be removed.
Actually, I just want to remove the first element(left the second element and the third element).



 Comments   
Comment by Asya Kamsky [ 22/Jan/14 ]

As a work-around, it's possible to make a positional update to the item you want to remove (to make it unique) and then $pull by that attribute.

Example:

db.coll.update({"_id":"123", "boys.name":"jhon"}, {$set:{"boys.$.name":"THIS"}});
db.coll.update({"_id":"123"}, {$pull:{"boys.name":"THIS"}})

If the element you want to remove happens to be first in array (like it is in this example) you ca use $pop operator with -1 (to remove one element from the front).

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