0

I am using Mongoose with Typescript; my current document look likes this:

{
    _id: 1,
    id: "a",
    markets: [{
        type: "car",
        price: 10000},
        {type: "toy",
        price: 10},...]
}
{
    _id: 2,
    id: "b",
    markets: [{
        type: "car1",
        price: 1023400},
        {type: "toy1",
        price: 1032},...]
}
{
    _id: 3,
    id: "c",
    markets: [{
        type: "car2",
        price: 10000},
        {type: "toy2",
        price: 1023},...]
}

I want to update particular {type: "car", price: 10000} this part base on id and type (given that id="a" and markets.type="car" before updating), which they should all be unique: for example: use {type: "car3", price: 11200} to update {type: "car", price: 10000}, how can I do it in Mongoose?

TungTung
  • 163
  • 7
  • 1
    Does this answer your question? [How do I update Array Elements matching criteria in a MongoDB document?](https://stackoverflow.com/questions/7967184/how-do-i-update-array-elements-matching-criteria-in-a-mongodb-document) – ray Jun 28 '23 at 10:02
  • no, I wish to update the entire object instead of a key value pair inside the object. @ray – TungTung Jun 29 '23 at 02:49

1 Answers1

1
db.collection.update({
  id: "a"
},
{
  $set: {
    "markets.$[element]": {
      type: "car3",
      price: 11200
    }
  }
},
{
  arrayFilters: [
    {
      element: {
        type: "car",
        price: 10000
      }
    }
  ]
})

mongoplayground

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Thank you, may I ask it is possible to add `upsert=true`, cause I tried, and can't add new object into the empty array inside `market` – TungTung Jun 28 '23 at 11:04