mongo db条件更新、推送数据

问题描述 投票:0回答:1

我的 MongoDB 数据库结构如下:

{
    accountName: "pippo",
    whishList: {
        element1: [
            { price: 25, time: '2024-02-20T20:00:00.000+00:00' },
            { price: 30, time: '2024-02-21T20:00:00.000+00:00' },
        ]
    }
}

我需要使用一个函数来更新此数据库,该函数接收价格作为参数,并仅当最后一个价格(最后一个元素的价格)时,才将具有此价格和当前时间(new Date())的对象推送到 element1 列表中称为元素 1) 的列表与此价格不同。如果在集合中找不到该文档,则应创建该文档(upsert true)。

我尝试了这段代码,但它不起作用:

async function updatePrice(id, element, price) {
    const filter = { 
        accountName: id,
        $expr: { $ne: [ {$last : `whishList.${element}`}.price , price ] }
    }
    const update = {     
        $push: {
            `whishList.${element}`: {
                value: valore,
                time: new Date()
            }
        }
    };

    await prova.updateOne(filter, update, { upsert: true });
}
arrays mongodb mongoose mongodb-query
1个回答
0
投票

您的

filter
标准不正确:

  1. 您不是指文档字段(缺少

    $
    )。

  2. 您没有正确从

    price
    数组中获取
    whishList.${element}
    最后一个元素。

您可以使用

$getField

const filter = {
  accountName: id,
  $expr: {
    $ne: [
      {
        $getField: {
          field: "price",
          input: {
            $last: `$whishList.${element}`
          }
        }
      },
      price 
    ]
  }
};

演示方法 1 @ Mongo Playground

或用点符号:

const filter = {
  accountName: id,
  $expr: {
    $ne: [
      {
        $last: `$whishList.${element}.price`
      },
      price 
    ]
  }
};

演示方法 2 @ Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.