简体   繁体   中英

Updating values in mongoDB collection using Node JS

I am new to mongoDB and and I found out how to insert and retrieve values in mongoDB using Node JS. When I retrieve values from collection, I get the values as below.

[{"1":["muthu","Pandiyan"],"_id":"5d7a23cdeee1c2ca3bf52a76"},{"2":["muthu","raj","ram","rifas"],"_id":"5d7a23cdeee1c2ca3bf52a77"},{"3":["pandiyan","jeni","raj"],"_id":"5d7a23cdeee1c2ca3bf52a78"}]

I would want to update values in the array of key "1" as ["muthu","Pandiyan","newuser"] and I tried the following code but I am not getting the desired result. I feel that I am doing the mistake in first parameter of the updatedOne query. Please correct me where I am missing.

var r = yield db.collection('dummy3qa').updateOne({"1"},{$addToSet:"newuser"}); assert.equal(null, err);

You can try this. Refer this https://docs.mongodb.com/manual/reference/method/db.collection.update/

db.dummy3qa.update(
   {'1'},
   { $addToSet:"newuser"}
)

This should work db.dummy3qa.update(_id:5d7a23cdeee1c2ca3bf52a76,{$addToSet:{1 : "newuser"}); . why yours did not work is because you are not specifying where it should update. Mongo needs to know where it should update, that is first and secondly you made a mistake in your $addToSet . why because from the doc you specify key and value as you update eg. {$addToSet: {key: value}} . for more in info https://docs.mongodb.com/manual/reference/operator/update/addToSet/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM