0

I have a data collection in mongodb like below:

{
    { "_id" : ObjectId("1"), "name" : "ABC", "group" : [ObjectId("11"), ObjectId("12"), ObjectId("13")]}
    { "_id" : ObjectId("2"), "name" : "DEF", "group" : [ObjectId("21"), ObjectId("22"), ObjectId("23")]}
}

I want to delete ObjectId("11") in the group field in document ObjectId("1").

I tried the code below:

aId = "1" 
bId = "11"
db.collection.updateOne({ _id: ObjectId(aId) }, { $pull: { group: { _id: ObjectId(bId) } } })

But failed.

I have also tried:

aId = "1" 
bId = "11"
db.collection.updateOne({ _id: aId }, { $pull: { group: { _id: bId } } })

But still failed to delete it.

Anything wrong with my code?

ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
Coolguy
  • 2,225
  • 12
  • 54
  • 81

1 Answers1

0

Use $unset like this:

db.products.update(
{ sku: "unknown" },
{ $unset: { quantity: "", instock: "" } })

This code will remove the fields quantity and instock from the firstdocument in the products collection where the field sku has a value of unknown. For more info