Add subdocument array element to subdocument array element in mongoDB

Is it possible? I have a C collection with an array of A1 attributes. Each attribute has an array of sub-attributes A2.

How to add a sub-document to a specific sub-document C.A1?

+4
source share
3 answers

Here is an example.

db.docs.insert({_id: 1, A1: [{A2: [1, 2, 3]}, {A2: [4, 5, 6]}]}) 

If you know the index of the subdocument that you want to insert, you can use dot notation with the index (starting at 0) in the middle:

 db.docs.update({_id: 1}, {$addToSet: {'A1.0.A2': 9}}) 

This leads to:

 { "A1" : [ { "A2" : [ 1, 2, 3, 9 ] }, { "A2" : [ 4, 5, 6 ] } ], "_id" : 1 } 
+8
source

Yes it is possible. If you post an example, I can more accurately show what the update request will look like. But here is a shot:

 db.c.update({ A1: value }, { $addToSet: { "A1.$.A2": "some value" }}) 

I haven't really tried this (I'm not right now in front of the Mongo instance right now), and I'm out of memory, but it should be very close.

0
source

Yes, $ push can be used for the same. Try the code below.

 db.c.update({ A1: value }, { $push: { "A1.$.A2": num }}); 
0
source

Source: https://habr.com/ru/post/1438439/


All Articles