1

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

1 Answer 1

4

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"} }})

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.