How to add a new key:value pair to existing sub object of a mongoDB document

问题: I am trying to add a new key:value pair to an existing object of mongoDB document, but no steps are helping me I tried $each, $push $addtoset but i understood those are f...

问题:

I am trying to add a new key:value pair to an existing object of mongoDB document, but no steps are helping me

I tried $each, $push $addtoset but i understood those are for arrays then i tried $det but it is updating the existing key:value pair with new key:value pair

Here is my document

    {
    test:"abc",
    test2:"cdf",
    test3:{ 1:"one"}
    }

if you observer test3 key in the above document i have already 1:"one" now i want to add new key value in the same object

Like

    {
    test:"abc",
    test2:"cdf",
    test3:{ 1:"one", 2:"two", 3:"three"}
    }

is it possible in mongoDB?

Here is the mongo Query

            let val = parseInt(DYNAMICVALUE)
              var changfeemaildot = (req.session.email).replace(/./g, '#')
              var seld = {
                _id: ObjectId(rx[0]._id)
              };
              var seldu = {

                $set:{
                emails: {
                   [changfeemaildot]: val
                }
              }
            };

              var collection = 
              connection.get().collection('problems');
              collection.update(seld, seldu, function (err, rail) {
              });

回答1:

You can use $set. So your code can be something like this

db.collection.update({<your_condition>}, {$set: {"test3.2": "two", "test3.3": "three"}});

In your case, it will be something like this

var seldu = {$set: {["emails." + changfeemaildot]: val}}
  • 发表于 2018-12-26 22:32
  • 阅读 ( 216 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除