4

Is this possible? I have a collection C, with an array of attributes A1. Each attribute has an array of subattributes A2.

How can I add a subdocument to a specific C.A1 subdocument ?

1
  • A before and after example document illustrating what you're looking for would be helpful. Commented Oct 8, 2012 at 16:42

3 Answers 3

8

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 you want to insert, you can use dot notation with the index (starting from 0) in the middle:

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

This results in:

{
    "A1" : [
        {
            "A2" : [
                1,
                2,
                3,
                9
            ]
        },
        {
            "A2" : [
                4,
                5,
                6
            ]
        }
    ],
    "_id" : 1
}
Sign up to request clarification or add additional context in comments.

1 Comment

"If you know the index of the subdocument you want to insert, " -- how would you know the index if you're inserting it?
0

Yes, this is possible. If you post an example I can show you more specifically what the update query would look like. But here's a shot:

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

I haven't actually tried this (I'm not in front of a Mongo instance right now) and I'm going off memory, but that should get you pretty close.

Comments

0

Yes, $push can be used to do the same. Try below given code.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.