2

I have a document like below:

{"_id":{"$oid":"5ce4c8cd4118952ffc4b3d2f"},
"test_id":{"$numberInt":"9002"},
"INTEGRATION":"myGeolocCountry",
"TEST_TOBE_DONE":{"AT_FF_COUNT":{"DEPENDENCY_FLAG":"N","EXECUTION_FLAG":"N"},"AT_FF_HEADER_CHECK":{"DEPENDENCY_FLAG":"N","EXECUTION_FLAG":"N"}}

I want to add one new object "SCHEDULER" after "TEST_TOBE_DONE" object.

After that I want to add one new LIST field after SCHEDULER object.

Position(field order) where I want to add is important

whoami - fakeFaceTrueSoul
  • 13,846
  • 4
  • 23
  • 39
SanjuB
  • 53
  • 1
  • 3
  • I think you should explain what you have tried so far (show your code!). What have you achieved and what is the specific problem? (doesn't do what you want, crashes, etc.) – pasbi Aug 25 '19 at 16:47
  • @SanjuB : Do you want help with python code plus mongoDB or just mongoDB query to do that ? – whoami - fakeFaceTrueSoul Aug 25 '19 at 17:24
  • @srinivasy Please give mongoDB query, I can try to python code based on the query. – SanjuB Aug 26 '19 at 04:04
  • @SanjuB : Did you try this ::>> db.getCollection('yourCollection').update({_id:ObjectId("5ce4c8cd4118952ffc4b3d2f")}, { $set:{SCHEDULER:{'someKey':1}, newList:[{someKey:1},{someOtherKey:2}]}}) – whoami - fakeFaceTrueSoul Aug 26 '19 at 04:46
  • 1
    @srinivasy it works . Thank you . I have one more question.. Newly added fields are getting added towards end of the document, can i add the newly added fields in the desired position. For example newList has to be added before the field "INTEGRATION" and after the field "test_id" – SanjuB Aug 26 '19 at 05:33
  • @SanjuB : that I'm not sure of whether you can update like that in one DB call, may be you can achieve by getting the doc out, adding your new fields and then replacing the document, but if it's for adding elements in an array field you can do using $postion, though you're not looking for this just saying !! though I don't recommend replaceOne unless needed(if you've entire document you can go ahead and replace existing), Check this :::> https://stackoverflow.com/questions/35848688/whats-the-difference-between-replaceone-and-updateone-in-mongodb – whoami - fakeFaceTrueSoul Aug 26 '19 at 05:56

1 Answers1

0

Please try this, a simple $set operator should add the new fields to the end of the document, as all of your fields are needed to be in the end - order them in the update operation, this should work :

db.getCollection('yourCollection').update({_id:ObjectId("5ce4c8cd4118952ffc4b3d2f")}, 
{ $set:{SCHEDULER:{'someKey':1}, newList:[{someKey:1},{someOtherKey:2}]}}) 

Ref : mongoDB Field Order

whoami - fakeFaceTrueSoul
  • 13,846
  • 4
  • 23
  • 39