Using positional operator for multiple levels of subdocuments [duplicate]

删除回忆录丶 提交于 2019-12-11 18:36:07

问题


I am using sub-documents in mongodb.

With one level of sub-documents, I can update documents with

Parent.findOneAndUpdate({ _id: parentId, 'children._id': childId }, {
  $set: {
    'children.$.name': name
  }
}, (err, doc) => {
  ...
});

but I have problems doing the same for another level of sub-documents, i.e.

Parent.findOneAndUpdate({ _id: parentId, 'children._id': childId, 'children.grandchildren._id': grandchildId }, {
  $set: {
    'children.$.grandchildren.$.name': name
  }
}, (err, doc) => {
  ...
});

Is the positional operator ($) limited to only 1 level of subdocuments?


回答1:


Positional Operator ($) only supports one level and also the first matching element. As a workaround what you can do is this,

$set: { 'children.$.grandchildren.0.name': name }

I think this issue is more clearly explained here



来源:https://stackoverflow.com/questions/39317976/using-positional-operator-for-multiple-levels-of-subdocuments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!