MongoDB在脚本中获取子文档变量

时间:2019-02-19 07:56:54

标签: mongodb

{
  "name": "Tim's Store",
  "location" : [
     {
        "city":"New York",
        "price": "123.45"
     },
     {
        "city":"London",
        "price": "46.63"
     },
  ]
}

我正在尝试通过以下脚本更改子文档数组中的价格类型。无法找到如何获取子文档数组长度。感谢帮助

var bulkOps = [];
db.pricelist.find({}).forEach(function (doc) {

  // How do i get subdocument array length and loop thru 
  // Is this the right way of getting the first element in the array ?
  var newValue = parseFloat(doc.location.0.price).toFixed(2);

  bulkOps.push({
    "updateOne": {
       "filter": { _id: doc._id },
       "update": { "$set": { "doc.price_tier.0.sale_price": newValue } }
    }
  });
})

db.pricelist.bulkWrite(bulkOps, { "ordered": true });

0 个答案:

没有答案