I have the following scheme in the database:

const randomSchema = new Schema({ elem1: { type: String , required: true } , elem2: { type: [Number] , default: [] , required: true } , }) 

More I removed as useless

As we can see - in the field elem2 we have an array of numbers.

What do I need to do:

Suppose I have the number 8855.

I need to check if there is such a number among the elements of this array, and if it is, then delete, and if not, add it to the array.

The code did not attach, because I could not write something a little closer to this functionality.

  • Retrieve an array from the database, check for the presence of a number and, depending on the result, make the desired action. I would do so - Dmytryk

1 answer 1

Try $ addToSet. Example:

 { _id: 1, letters: ["a", "b"] } 

 db.test.update( { _id: 1 }, { $addToSet: {letters: "c" } } ) 

 { _id: 1, letters: [ "a", "b", "c" ] } 

Link to dock - link

  • And if "c" is already in the array, "c" will be deleted? - Dmytryk
  • Sorry, I missed about "delete item if exists". Indeed, probably the right decision would be to get a document -> make a filter for an array -> well, and update the document with the necessary array. - Valera Checha