2

For a web application form i'm trying to add data to mongo collection on click of submit. my mongo collection is as below :

collection1:

 { "_id" : ObjectId("56e0a3a2d59feaa43fba49d5"), "timestamp" : ISODate("2017-11-18T10:23:29.620Z"), "City" : "London ", "LDE" :  "LDE-1234, LDE-345, LDE-456" }
 { "_id" : ObjectId("56e0a3a2d59feaa43fba49d6"), "timestamp" : ISODate("2016-12-18T10:23:29.620Z"), "City" : "Berlin", "LDE" : "LDE-444, LDE-3445, LDE-456" }
 { "_id" : ObjectId("56e0a3a2d59feaa43fba49d7"), "timestamp" : ISODate("2016-12-18T10:23:29.620Z"), "City" : "Dublin", "LDE" : "LDE-444, LDE-3445, LDE-7899, LDE-0909" }

In my form.html i have 2 input (City and LDE) 2 possibilities of adding value to db collection1 would be

Same City but new LDE value , then validate if LDE is present and update the document from collection . New City , then insert it into collection1.

The Update query i'm trying is as below :

 db.collection1.update({"City": "Dublin"}, { '$set' : {"LDE": "LDE-4443"}}), 

its changing the collection to : { "_id" : ObjectId("56e0a3a2d59feaa43fba49d7"), "timestamp" : ISODate("2016-12-18T10:23:29.620Z"), "City" : "Dublin", "LDE" : "LDE-4443" }

what I want is :

 { "_id" : ObjectId("56e0a3a2d59feaa43fba49d7"), "timestamp" : ISODate("2016-12-18T10:23:29.620Z"), "City" : "Dublin", "LDE" : "LDE-444, LDE-3445, LDE-7899, LDE-0909, LDE-4443" }

Also, Can this be done in one query both insert and update depending on the City value (without for or if loop)

Rachel
  • 247
  • 6
  • 19
  • Also see ["Set fields in Embedded Documents"](https://docs.mongodb.com/manual/reference/operator/update/set/#set-fields-in-embedded-documents) which is actually a sub-section of the documentation for `$set`. – Neil Lunn Jun 07 '18 at 06:18
  • @NeilLunn i do not want to set some value value to the field. I want to update the list (add a new value to already existing set). – Rachel Jun 07 '18 at 07:04
  • You cannot do that, and that's just a different duplicate even though the "embedded access" thing stays the same. You really want an "array" here instead, since "re-writing a string" involves reading the document in order to modify, and that's not an atomic update. – Neil Lunn Jun 07 '18 at 07:09
  • oh !! what would be better solution in that case. So that every submit im update to update the collection. – Rachel Jun 07 '18 at 08:44
  • Read the linked answer showing `$push`. You can "append to arrays" but not to "strings". So make your data an array instead. Far more practical if you want to append things. – Neil Lunn Jun 07 '18 at 08:45

0 Answers0