2

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

1
  • 1
    Would be helpful if you can provide your sample data and expected data in text instead of images Commented Nov 1, 2021 at 1:15

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ok! Thank you very much! I was searching on the web before posting this, but always pop up the "update" option without the $push operator!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.