mongodb update许多查询存储字符串而不是引用

olhwl3o2  于 2023-03-17  发布在  Go
关注(0)|答案(1)|浏览(107)

这是我的产品系列

{
    "_id" : ObjectId("640de93a469aa38cb4ceec7e"),
    "product_title" : "Colorful Pattern Shirt",
    "product_sku" : "shirt003",
    "product_color" : "white",
    "product_size" : "32",
    "product_brand" : "nike",
    "product_description" : "cotton material good shirt",
    "product_price" : NumberInt(3000),
    "product_warranty" : "1 Year AL Jazeera Brand Warranty",
    "product_return" : "30 Day Return Policy",
    "product_quantity" : "10",
    "product_category" : "Womens",
    "delivery[]" : [
        "Cash On Delivery",
        "Credit Card",
        "Debit Card",
        "UPI",
        "Paypal"
    ],
    "offerPrice" : 888.0,
    "isActive" : true,
    "offerEndDate" : "2023-03-10"
}
  • 它有一个名为offerPrice的字段,错误是在将offerPrice设置为product_price时 *
  • 这是更新查询**
const moment = require('moment')
      // Calculate the date when the offer ends
      const offerEndDate = moment().subtract(1, 'days').toDate()
      // Convert offerEndDate to a string in the format 'YYYY-MM-DD'
      const isoOfferEndDate = moment(offerEndDate).format('YYYY-MM-DD')
const result = await db.get().collection(collection.PRODUCT_COLLECTION).updateMany(
  {
    offerEndDate: { $lt: isoOfferEndDate }
  }
  {
    $unset: { offerEndDate: 1 },
    $set: {
      offerPrice: "$product_price"
    }
  }
)
  • 但在执行此查询后。报价价格存储在数据库中 * "offerPrice" : "$product_price",
  • 我也试过$$ROOT.product_price
9avjhtql

9avjhtql1#

使用$fieldName引用文档中的字段是聚合操作,在常规更新中无效。
您可以将这种类型的操作用于聚合形式的更新,传递一个聚合阶段数组而不是一个更新文档:

.updateMany(
  {
    offerEndDate: { $lt: isoOfferEndDate }
  },
  [
   {$unset: "offerEndDate" },
   {$set: {offerPrice: "$product_price"}}
  ]
)

Playground

相关问题