mongodb 如何使用Mongoose更新数组中的整个对象

gab6jxml  于 2023-06-29  发布在  Go
关注(0)|答案(1)|浏览(153)

我使用Mongoose和Typescript;我的当前文档看起来像这样:

{
    _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},...]
}

我想根据idtype更新特定的{type: "car", price: 10000}部分(在更新之前,假设id=“a”和markets.type=“car”),它们应该都是唯一的:例如:使用{type: "car3", price: 11200}更新{type: "car", price: 10000},在Mongoose中如何操作?

8gsdolmq

8gsdolmq1#

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

mongoplayground

相关问题