mongodb - push item in sub document -
i have simple collection. want push item in question, gives exception.how can resolve ?
/* 1 */ collection data
{ "_id" : objectid("557e8c93a6df1a22041e0879"), "questioncount" : 2.0000000000000000, "questions" : [ { "_id" : objectid("557e8c9ba6df1a22041e087a"), "datasource" : [], "datasourceitemcount" : numberlong(0) }, { "_id" : objectid("557e8c9fa6df1a22041e087b"), "datasource" : [], "datasourceitemcount" : numberlong(0) } ], "name" : "er" } ( id =557e8c93a6df1a22041e0879 , question id = 557e8c9fa6df1a22041e087b)
db.getcollection('forms').update({ "_id": objectid("557e8c93a6df1a22041e0879"), "questions._id": objectid("557e8c9fa6df1a22041e087b") }, { "$push": { "questions.datasource": { "_id": objectid("557e8e5ea6df1a27b403ff6b"), "creationdate": isodate("2015-06-15t08:35:42.923z"), "isactive": true, "text": "op", "value": "op" } } }) cannot use part (questions of questions.datasource) traverse element ({questions: [ { _id: objectid('557e8c9ba6df1a22041e087a'), creationdate: new date(1434356891784), isactive: true, name: "uıo", isrequired: false, questiontype: 1, answerinputtype: 1, answervalidationpattern: null, answervalidationmessage: null, questionorder: 1, datasource: [], datasourceitemcount: 0 }, { _id: objectid('557e8c9fa6df1a22041e087b'), creationdate: new date(1434356895695), isactive: true, name: "ıu", isrequired: false, questiontype: 2, answerinputtype: 1, answervalidationpattern: null, answervalidationmessage: null, questionorder: 2, datasource: [], datasourceitemcount: 0 } ]})
you need positional $ operator in update portion of statement:
db.getcollection('forms').update( { "_id" : objectid("557e8c93a6df1a22041e0879"), "questions._id" : objectid("557e8c9fa6df1a22041e087b") }, { "$push" : { "questions.$.datasource" : { "_id" : objectid("557e8e5ea6df1a27b403ff6b"), "creationdate" : isodate("2015-06-15t08:35:42.923z"), "isactive" : true, "text" : "op", "value" : "op" } } } ) it identifies index of found item want update.
whilst okay $push operations nested array structure, find "nested arrays" not updating. main problem here "positional operator" can match index of "first" or "outer" array only. not possible match position of inner array element , update it.
i recommend changing structure "flatten" single array more suited these operations.
Comments
Post a Comment