【问题标题】:For each MongoDB document, add a new variable that increments对于每个 MongoDB 文档,添加一个递增的新变量
【发布时间】:2020-12-29 19:51:05
【问题描述】:

我有一个包含以下文档的集合:

[{_id: abc, name: "foo"}, {_id: def, name: "bar"}, {_id: ghi, name: "baz"}]

我想更改该集合中的每个文档,使其具有一个新字段,该字段是唯一的,并且包含一个字母和一个数字,每个文档的数字都会增加。所以我想要这个:

[{_id: abc, name: "foo", customId: "m1"}, {_id: def, name: "bar", customId: "m2"}, {_id: ghi, name: "baz", customId: "m3"}]

我尝试使用投票最多的答案in this question,但它只有一个数字,它是数组中的索引,但我想要一个字母和它旁边的数字。

我将 NodeJS 和 Express 与 mongoose 包一起使用。 我不介意答案是使用 javascript 代码还是 mongo cli 命令。

非常感谢任何帮助,在此先感谢。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我假设您需要更新现有表,还需要为即将到来的数据创建计数器字段,

    function update() { //updating existing table
        user.aggregate(
            [{
                $match: {
                    "counter": { $exists: false }
                }
            }],
            function (err, res) {
                if (err) {
                    console.log(err)
                }
                var i = 0;
                var newId;
                res.forEach((element, index) => {
                    i = i + 1;
                    newId = "count" + i
                    user.update(
                        { id: element.id },
                        { $set: { "Counter": newId } }
                    );
    
                });
            })
    }
    
    function create(userparam) {//while creating new table
        autonumber.find({}, function (err, res) {
            let counter_value = "Count" + res[0].incrementer
            //assuming  incrementer to be feild in autonumber table
            const user = new User(userparam);
            user.Counter = counter_value;
            return await user.save()
        })
    }
    

    我是初学者,所以如果这段代码效率低下或错误......提前抱歉。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 2012-02-20
      • 1970-01-01
      • 2015-05-06
      相关资源
      最近更新 更多