2

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) {
              });

2 Answers2

5

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}}
Nimish Gupta
  • 971
  • 7
  • 17
  • $set is removing old value and adding new value –  Dec 24 '18 at 21:11
  • at every iteration i need to insert new value that is the problem –  Dec 24 '18 at 21:11
  • Can you show me your $set query? Because according to its documentation it only updates the document. – Nimish Gupta Dec 24 '18 at 21:13
  • var seldu = { $set:{ emails: { [DYNAMICKEY]: DYNAMICVALUE } } }; –  Dec 24 '18 at 21:16
  • 4
    Ok , so here you are completely overriding the the object, you can do something like this `{ $set:{ ["emails." + DYNAMICKEY]: DYNAMICVALUE } };` – Nimish Gupta Dec 24 '18 at 21:19
  • In the answer, I have not updated the whole object, but I have added individual keys. – Nimish Gupta Dec 24 '18 at 21:20
  • i tried your solution still it is updating old value, and emails are dynamic FYI –  Dec 24 '18 at 21:24
  • I tried my solution in local mongo shell its not updating the whole object, its just adding the value, check this [output](https://www.dropbox.com/s/bm2w7lc5mv8yydh/Screenshot%202018-12-25%2003.04.26.png?dl=0), are you doing something similar to this? – Nimish Gupta Dec 24 '18 at 21:35
  • I am really worrying now. why that is not working for me? –  Dec 24 '18 at 21:38
  • Can you paste some snippet of your code and update your question? – Nimish Gupta Dec 24 '18 at 21:39
  • Updated, please help. –  Dec 24 '18 at 21:43
  • I still not understanding why you added `email.` as prefix when the email is dynamic –  Dec 24 '18 at 21:51
  • but email is the key of the object in which you want to add the dynamic key:value, right? If yes, that's why I prefixed your new key with emails, such that your new key is part of emails object. – Nimish Gupta Dec 24 '18 at 21:55
0

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

  const { Types, connection } = require("mongoose");

  const productList = await connection.collection('products').find({}).toArray()
    productList.forEach(async function(myDoc) {
        await connection.collection('products').
        updateOne({ productId: Types.ObjectId(myDoc.productId) }, {
            $set: {
                productDisplayId: 'anything you want'
            }
        });
    });