2

I am new to mongo now I trying to do in MongoDB push and pull query concept in the array. I want to pull all object and push the new object into an array while using pull alone its working fine and same push alone working fine but i used both in single query i tired but not able to achieve my need help to solve this Note:UIList array is Dynamic

My Query

 db.getCollection('roles').update(
    { "_id": ObjectId("5bd6b1dc552a2a3ed0bde948") },
    { "$pull": { "UIList": {  } } },
    { "$push":  {$set: "UIList": { "field1": "1234", "field2": "12345" } } }) //Not working
Community
  • 1
  • 1
jose
  • 1,044
  • 1
  • 12
  • 35

1 Answers1

1

As design you can't apply multiple update modifiers to the fields. You can use $set with array which will overwrite the existing array values.

Something like

db.getCollection('roles').update(
    {"_id": ObjectId("5bd6b1dc552a2a3ed0bde948") },
    {"$set":{"UIList":[{"field1":"1234","field2": "12345"}]}}
)
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • thanks but my values are dynamic i am not do any hardcode i forgot this in question that's why i am trying in pull and push method idea? – jose Oct 29 '18 at 10:50
  • You can pass anything to $set as long it resolves to array like `{$set:{UIList:my dynamic array }}`. – s7vr Oct 29 '18 at 10:51