Using positional operator for multiple levels of s

2019-09-10 11:59发布

This question already has an answer here:

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条回答
再贱就再见
2楼-- · 2019-09-10 12:31

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

查看更多
登录 后发表回答