Shaleesh Madhavan
Shaleesh Madhavan

Reputation: 47

how to use update query in mongoDb?

I have few documents in user Collection like below .I need to update ancestors field alone,Need to add few more values.

db.users.find() 
 {
   "_id" : ObjectId("5d9fd81f3d598088d2ea5dcc"),
   "DOB" : ISODate("1979-05-23T00:00:00Z"),
    "userImage" : "sathish_1589780950636.jpeg",
    "createdDateTime" : ISODate("2016-02-01T09:43:27Z"),
    "modifiedDateTime" : ISODate("2017-04-26T15:57:09Z"),
    "status" : "active",
    "ancestors" : [
        ObjectId("5d9fd81b3d598088d2ea5dc7")
    ],
    "parent" : ObjectId("5d9fd81b3d598088d2ea5dc7")
}

When i tried the below query.

db.users.update({"_id" : ObjectId("5d9fd81f3d598088d2ea5dcc")},{$set:{"ancestors" : [
        ObjectId("5f45f9491ff4bd74ec754e3a"),
        ObjectId("5d9fd8203d598088d2ea5dcd"),
        ObjectId("5d9fd8723d598088d2ea5e43")
    ]}})

It just replace the old one and completely adding the new one.

I need the result to be like this .old data should also remain and new one should be added.

"ancestors" : [
        ObjectId("5f45f9491ff4bd74ec754e3a"),
        ObjectId("5d9fd8203d598088d2ea5dcd"),
        ObjectId("5d9fd81b3d598088d2ea5dc7"),
        ObjectId("5d9fd8723d598088d2ea5e43")
    ]

This update query should be done in all documents in that collection. the above mentioned 3 values to be added in all documents, instead of find and update, I should be doing bulk updated

Upvotes: 0

Views: 48

Answers (2)

Blaise Vellozzo
Blaise Vellozzo

Reputation: 26

I think you can run the following:

db.users.updateOne({"_id" : ObjectId("5d9fd81f3d598088d2ea5dcc")},{$addToSet:{"ancestors" :{ $each: [
        ObjectId("5f45f9491ff4bd74ec754e3a"),
        ObjectId("5d9fd8203d598088d2ea5dcd"),
        ObjectId("5d9fd8723d598088d2ea5e43")
    ]}}})

ref: https://docs.mongodb.com/manual/reference/operator/update/each/

Upvotes: 1

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

 You can use mongodb method $push

db.users.update({"_id" : ObjectId("5d9fd81f3d598088d2ea5dcc")},
{ $push: {ancestors:ObjectId("5f45f9491ff4bd74ec754e3a") } })

[check doc][1]


 [1]: https://docs.mongodb.com/manual/reference/operator/update/push/

Upvotes: 1

Related Questions