【问题标题】:How to calculate a field in mongodb如何计算mongodb中的字段
【发布时间】:2021-05-23 04:54:58
【问题描述】:

您好,我正在尝试在 mongoDB 中创建一个计算字段,但是我收到此错误: MongoError: '$add' 中的美元 ($) 前缀字段 '$add' 对存储无效。

这是代码:

router.post('/char1btn', ensureAuthenticated, function(req, res) {
    const {
        MongoClient
    } = require("mongodb");
    //Replace the uri string with your MongoDB deployment's connection string.
    const uri =
        'mongodb+srv://test:test1234@databasetest.5f9jh.mongodb.net/Databasetest?retryWrites=true&w=majority';
    const client = new MongoClient(uri);
    async function run() {
        try {
            await client.connect();
            const database = client.db("Databasetest");
            const collection = database.collection("users");
            //create a filter for charactername to update
            const filter = {
                characterimg: ""
            };
            // this option instructs the method to create a document if no documents match the filter
            const options = {
                upsert: false
            };
            const updateDoc = {
                $set: {
                    health: 150,
                    attack: 3,
                    defence: 3,
                    endurance: 10,
                    characterimg: "https://i.ibb.co/MPg2SMp/Apocaliptic1.png",
                },
                $set: {
                    $add: ["$power", "$attack", "$defence", {
                        $devide: ["$endurance", 3]
                    }]
                }
            }
            const result = await collection.updateOne(filter, updateDoc, options);
            console.log(
                `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
            );
        } finally {
            res.redirect('/main');
            await client.close();
        }
    }
    run().catch(console.dir);
})

有谁知道如何解决这个问题?

【问题讨论】:

  • 您没有提供任何要设置的字段名称。
  • 所以你的意思是我必须这样做: $set: $" power" { $add : [ "$power", "$attack" ,"$defence" , { $devide : ["$endurance", 3]}]} } 或者你能给我举个例子。

标签: javascript mongodb


【解决方案1】:

根据@WernfriedDomscheit 的评论更新

如果您使用的是 MongoDB 版本 > 4.2,那么您可以在update 中使用管道所以更新查询如下:

db.users.updateOne({},
  [
    {
      $set: {
        attack: 1,
        defence: 2,
        endurance: 3
      }
    },
    {
      $set: {
        power: {
          "$add": ["$attack", "$defence", { $divide: ["$endurance", 3] }]
        }
      }
    }
  ],
  { upsert: true }
);

会有输出:

{
    "_id" : ObjectId("603124a22391a75d9a2ddec0"),
    "attack" : 1,
    "defence" : 2,
    "endurance" : 3,
    "power" : 4
}

所以在你的情况下:

const updateDoc = [
  {
    $set: {
      health: 150,
      attack: 3,
      defence: 3,
      endurance: 10,
      characterimg: "https://i.ibb.co/MPg2SMp/Apocaliptic1.png",
    }
  },
  {
    $set: {      
      power: {
        $add: ["$attack", "$defence", { $divide: ["$endurance", 3] }]
      }
    }
  }
];

【讨论】:

  • 代码似乎可以运行,但功率输出保持为 0,公式应为:功率 = 攻击 + 防御 + 耐力 / 3。为什么会发生这种情况,因为它不应该返回 0。@Dheemanth巴特
  • 您的代码中有错字,它是$divide 而不是$devide
  • 是的,但是我运行了你的代码,由于某种原因,功率输出仍然为 0。
  • 那没问题,可能我这边有什么问题。我会试着弄清楚。
  • 不能在同一阶段使用变量$attack$defence
【解决方案2】:

试试这个:

const updateDoc = [
   {
      $set: {
         health: 150,
         attack: 3,
         defence: 3,
         endurance: 10,
         characterimg: "https://i.ibb.co/MPg2SMp/Apocaliptic1.png",
      }
   },
   {
      $set: {
         result: { $sum: ["$power", "$attack", "$defence", { $divide: ["$endurance", 3] }] }
      }
   }
];
const result = await collection.updateOne(filter, updateDoc, options);

您需要两个$set 阶段。否则$sum: [...](或$add)将使用旧值,或者如果之前不存在字段则失败。还要注意updateDoc需要是一个数组,见updateOne()

【讨论】:

  • 谢谢你的工作,有没有办法只显示结果后的第一个数字?就像现在它显示:9,333333333333334,但只有 9,3 会更好。
  • $round
  • 好吧,但似乎我需要给出一个具体的数字.. 我试图四舍五入 $sum 或 power 场,但两者似乎都不起作用。功率:{ $sum: ["$power", "$attack", "$defence", { $divide: ["$endurance", 3] }, { $round: [power, 2] }] } , 功率: { $sum: ["$power", "$attack", "$defence", { $divide: ["$endurance", 3] }, { $round: [$sum, 2] }] } 参考错误:功率未定义 ReferenceError: $sum 未定义
猜你喜欢
  • 2018-06-20
  • 2022-12-08
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
相关资源
最近更新 更多