0

I am currently learning mongoDB, and saw this feature you can use $each with $push to push multiple values into the database. Here's exact command I used:

`bookstore> db.books.updateOne({_id: ObjectId("63e099a98816e61af42af7ad")}, {$push: {genres: {$each: ["1", "2"]}}})`

Now I was wondering if the opposite if this command was possible, so replaced $push with $pull and go this error:

db.books.updateOne({_id: ObjectId("63e099a98816e61af42af7ad")}, {$pull: {genres: {$each: ["1", "2"]}}})

MongoServerError: unknown top level operator: $each. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.

I did try using $get and it yielded another error. Does anyone know how to do this? Many thanks in advance! (I know I can PULL one by one, but I want to explore features which make the day a little bit easier)

update: I tried directly using $pull on the elements. The resultant was this.

bookstore> db.books.updateOne({_id: ObjectId("63e099a98816e61af42af7ad")}, {$pull: {genres: ["1", "2"]}})

{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 0, upsertedCount: 0 }

even though the code didn't give an error, and it did match with a value, the modifiedCount is still 0.

  • https://www.mongodb.com/docs/v5.0/reference/operator/update/pullAll/ – Noel Feb 06 '23 at 11:50
  • thank you @Noel this article helped. the correct command is: db.books.updateOne({_id: ObjectId("63e099a98816e61af42af7ad")}, {$pullAll: { genres: ["1", "2"]}}) I don't know how to mark your answer as the correct answer, but it is. – Dr.Drunkenstein Feb 06 '23 at 12:23

0 Answers0