Code Chapter
Code Chapter

Reputation: 37

Remove element in array by value | MongoDB | NodeJS

I have a mongoDB with a collection called users. Each element has a usrName, UserID, token, and then 3 arrays which are friends, incoming and outgoing (all of them relative to 'friends'). Im looking for something like:

db.collection('users').find({user:"some userID"}).update or something similar.

I expect the search for the correct element (by the id) and then remove some element from the 'incoming' array by the value. (its a string array)

here is the DB structureenter image description here

Upvotes: 1

Views: 2701

Answers (1)

Frank Rose
Frank Rose

Reputation: 411

The update would look something like this:

db.collection('users').updateOne({user: "some userID"}, {$pull: { incoming: "removeThisValue" }})

$pull takes an object which describes the array field you are pulling from and the criteria you are using to remove it. Since you said it's a string array you'll be looking for equality. But just note that you could also use mongodb operators such as $gte, $lt and others if working with different values.

If you were removing multiple values from the array at once:

db.collection('users').updateOne({user: "some userID"}, {$pull: { incoming: { $in: ["removeMe", "removeMeToo"] } }})

Its also worth noting if you ever have an array of documents you could also target specific key/values. Let's say a user has an array of hobbies where each hobby has "title" and "timePerWeek" keys. We could remove the hobby with the title of "Gaming" like this:

db.collection('users').updateOne({user: "some userID"}, {$pull: { hobbies: {title: "Gaming"} }})

Upvotes: 4

Related Questions