Home > Mobile >  MongoDB: Updating a document with existing fields using aggregation
MongoDB: Updating a document with existing fields using aggregation

Time:11-02

I am new to mongodb, I am learning from some Udemy courses and I want to know how I can update a document existing field without overwriting it.

I have the following collection with these documents:

enter image description here

I want to add new warehouses in the "item":"drafts" within the stock field.

What I am trying is:

enter image description here

And giving the output it seems that is working, but when I do again db.matrices.find(), what I get is the exactly same output that in the first image.

How can I update it? I have tried also the update method, but does not do what I want to do.

Thanks!

PD: I am using linux mint, with mongo v5.0.3, and mongosh v1.1.1

CodePudding user response:

You are using the aggregate pipeline, this does not update the document in the DB, it just retrieves the result. starting in Mongo version 4.2 you can now use an aggregation pipeline ( with some limitations ) to update a document, like so:

db.collection.updateOne({
  item: "drafts"
},
[
  {
    $set: {
      stock: {
        $concatArrays: [
          "$stock",
          [
            {
              "warehouse": "A",
              qty: 20
            }
          ]
        ]
      }
    }
  }
])

Mongo Playground

I will just say that this specific update is very simple, there is no need to use an aggregation pipeline for it. a simple use of the $push operator in the update field will suffice in a "normal" update:

db.collection.updateOne({
  item: "drafts"
},
{
  $push: {
    stock: {
      "warehouse": "A",
      qty: 20
    }
  }
})

Mongo Playground

  • Related