D
D
Danya Kozlovskiy2021-11-16 04:07:45
MongoDB
Danya Kozlovskiy, 2021-11-16 04:07:45

How to add elements from an array that are not in the array in MongoDB?

Hey! I take an array of strings as input and after that I want to add each element to the array in the document, but only if the element does not exist in the already created array (in mongodb), i.e. if the document already has an array with values ​​1,2,3,4, and I give 2,3,5,6 as input, then 5 and 6 should be added. I tried adding via "$addToSet", but it works well only if the array in mongodb has types like int, string, etc., and I have objects there and in the end it scores that the element is already in the database.

Sample input (should be added only "[email protected]", "[email protected]"):

["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]


Document in MongoDB:
{
    "username": "testuser",
    "receiver_list": [{
        "_id": "ObjectID(\"619304749cf306ab40a95310\")",
        "receiver": "[email protected]"
    }, {
        "_id": "ObjectID(\"619304749cf306ab40a95311\")",
        "receiver": "[email protected]"
    }, {
        "_id": "ObjectID(\"619304749cf306ab40a95312\")",
        "receiver": "[email protected]"
    }]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2021-11-16
@yarkov

It's easier to combine the array from the database and from the query, and then remove the repetitions through new Set. Well, since we're talking about an array of strings.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question