Lakshya Gupta
Lakshya Gupta

Reputation: 13

Update whole child element of an array field of an document in mongodb nodejs

Considering the following document, i want to update whole field of dataset with _id:123,

  "data": {
            "_id": "1234546",
            "dataset": [
                {
                    "_id": "123",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "787",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "898",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
                {
                    "_id": "564",
                    "el2": "asd",
                    "el3": "sd",
                    "el4": "gfdd",
                    "el5": "asdfa",
                },
            ]
        }

I want to update all fields of an array element by using _id of field.

I am using

    getDB.collection ('data').findOneAndUpdate(
    { _id: new ObjectId(data.userId),
        "dataset._id":new ObjectId(data.dataset),
    },
    { $set: { "userAddress.$":newdataset } },
    {returnOriginal:false}});

Please suggest some good option to update it.

Thanks in advance.. :)

Upvotes: 1

Views: 341

Answers (1)

Farouk Elkholy
Farouk Elkholy

Reputation: 943

If you want to just update the document on the db server without fetching it, you could use update instead of findOneAndUpdate.

Here a way to do it.

collection('data').update({
      _id:<_id>,
      "dataset._id":<dataset._id>
    },{
      $set:{
        "dataset.$.el2":<el2>,
        "dataset.$.el3":<el3>,
        "dataset.$.el4":<el4>,
        "dataset.$.el5":<el5>
      }
    })

Upvotes: 1

Related Questions