Mongodb: update an object inside an array

Viewed 148

I have the current mongo collection and need to find and specific id inside an array and update its value.

{
  "_id" : ObjectId("111fe6813abdeb1505f5111"),
  "objectIdUser" : ObjectId("111fe6813abdeb1505f5111"),
  "objectIdClasses" : [ 
      {
          "objectIdClass" : ObjectId("111fe6813abdeb1505f5111")
      }
  ],
}

I tried to use the following query but It never updates.

db.classes.findOneAndUpdate(
  {
    objectIdUser: ObjectId("111fe6813abdeb1505f5111"),
    "objectIdClasses.objectIdClass": ObjectId('111fe6813abdeb1505f5111')
  },
  { 
    $set: 
    {
      "objectIdClasses.$.objectIdClass": ObjectId('111fe6813abdeb1505f5111')
    }
  }
);

The records exists, but I always get a null value and the value is never updated.

1 Answers

Follow the below steps carefully;

db.<collectionName>.updateOne(filter, updateDoc, options);
  • the filter go defines the document you want to change, just like the find.
  • the updateDoc defines the new changes
  • the options instruct the method to create a document if no documents match the filter

Example:
I have a database of shop collection with the following data in a products collection

{ "_id" : 1, "name" : "Pen", "price" : 1.2 }

If I want to change the "price" to of "Pen" to 5.0 then:

db.products.updateOne({name: "Pen"}, {$set: {price: 5.0}}, {upsert: true});

Note: all your changes should be inside the <$set> object

Related