2

I've searched across the site of course, but it seems that there is confusing terminology regarding what is a "subdocument"...

Imagine we have two collections (Pages and Items) with the following schemas:

Item:
  _id: ObjectId
  name: String

Page:
  _id: ObjectId
  titles: [ {value: String} ]
  items: [ Relationship <Item>, many: true ]

If I try to update "titles" sub-array - everything works fine:

db.pages.update({_id: ...}, { $set: {"titles.0.value": "x"} });

But if I try to update "items" sub-documents-array - it fails:

db.pages.update({_id: ...}, { $set: {"items.0.name": "x"} });

The error is returned:

"cannot use the part (0 of items.0.name) to traverse the element"

If I try to replace "0" with a "$" like this:

db.pages.update({_id: ...}, { $set: {"items.$.name": "x"} });

Another error is returned:

"The positional operator did not find the match needed from the query. Unexpanded update: items.$.name"

How to correctly update the value inside the related subdocument?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Artico
  • 101
  • 6
  • `items: [ Relationship , many: true ]`. Relationships have nothing at all to do with MongoDB. This is a property of whatever driver/framework you are using. If that is even true. Show an actual document you are trying to update in your question. – Neil Lunn May 26 '17 at 09:52
  • I see the point now... Internally it's just an array with related ObjectIds: "items": [ ObjectId("5925a2082843750cc6af6b62"), ObjectId("5925a2152843750cc6af6b63") ] – Artico May 26 '17 at 09:59
  • Yep. You are probably actually using mongoose. That means you actually should be updating the "documents" in the collection that they live in instead of trying to update from this collection. That is how that works. – Neil Lunn May 26 '17 at 10:02
  • Is there any way to achieve that probably using aggregation? – Artico May 26 '17 at 10:04
  • Nope. MongfoDB does not do joins. Aggregation does not modify things. If you need to select the children based on the parent, then you query the parent and perform another query to update the children ( on their collection ) identified by the `ObjectId` values present in the parents array. – Neil Lunn May 26 '17 at 10:07
  • Thank you! Would you mind to post an answer so I can accept it? – Artico May 26 '17 at 10:10
  • That `0` is very suspicious. http://xyproblem.info/ ? – Karoly Horvath May 26 '17 at 10:15
  • There is no problem with `0` when you deal with a sub-array. This is documented MongoDB behaviour. – Artico May 26 '17 at 10:54

0 Answers0