MongoDB: How do I update a single subelement in an array, referenced by the index within the array?












52















I'm trying to update a single subelement contained within an array in a mongodb document. I want to reference the field using its array index (elements within the array don't have any fields that I can guarantee will be unique identifiers). Seems like this should be easy to do, but I can't figure out the syntax.



Here's what I want to do in pseudo-json.



Before:



{
_id : ...,
other_stuff ... ,
my_array : [
{ ... old content A ... },
{ ... old content B ... },
{ ... old content C ... }
]
}


After:



{
_id : ...,
other_stuff ... ,
my_array : [
{ ... old content A ... },
{ ... NEW content B ... },
{ ... old content C ... }
]
}


Seems like the query should be something like this:



//pseudocode
db.my_collection.update(
{_id: ObjectId(document_id), my_array.1 : 1 },
{my_array.$.content: NEW content B }
)


But this doesn't work. I've spent way too long searching the mongodb docs, and trying different variations on this syntax (e.g. using $slice, etc.). I can't find any clear explanation of how to accomplish this kind of update in MongoDB.










share|improve this question





























    52















    I'm trying to update a single subelement contained within an array in a mongodb document. I want to reference the field using its array index (elements within the array don't have any fields that I can guarantee will be unique identifiers). Seems like this should be easy to do, but I can't figure out the syntax.



    Here's what I want to do in pseudo-json.



    Before:



    {
    _id : ...,
    other_stuff ... ,
    my_array : [
    { ... old content A ... },
    { ... old content B ... },
    { ... old content C ... }
    ]
    }


    After:



    {
    _id : ...,
    other_stuff ... ,
    my_array : [
    { ... old content A ... },
    { ... NEW content B ... },
    { ... old content C ... }
    ]
    }


    Seems like the query should be something like this:



    //pseudocode
    db.my_collection.update(
    {_id: ObjectId(document_id), my_array.1 : 1 },
    {my_array.$.content: NEW content B }
    )


    But this doesn't work. I've spent way too long searching the mongodb docs, and trying different variations on this syntax (e.g. using $slice, etc.). I can't find any clear explanation of how to accomplish this kind of update in MongoDB.










    share|improve this question



























      52












      52








      52


      10






      I'm trying to update a single subelement contained within an array in a mongodb document. I want to reference the field using its array index (elements within the array don't have any fields that I can guarantee will be unique identifiers). Seems like this should be easy to do, but I can't figure out the syntax.



      Here's what I want to do in pseudo-json.



      Before:



      {
      _id : ...,
      other_stuff ... ,
      my_array : [
      { ... old content A ... },
      { ... old content B ... },
      { ... old content C ... }
      ]
      }


      After:



      {
      _id : ...,
      other_stuff ... ,
      my_array : [
      { ... old content A ... },
      { ... NEW content B ... },
      { ... old content C ... }
      ]
      }


      Seems like the query should be something like this:



      //pseudocode
      db.my_collection.update(
      {_id: ObjectId(document_id), my_array.1 : 1 },
      {my_array.$.content: NEW content B }
      )


      But this doesn't work. I've spent way too long searching the mongodb docs, and trying different variations on this syntax (e.g. using $slice, etc.). I can't find any clear explanation of how to accomplish this kind of update in MongoDB.










      share|improve this question
















      I'm trying to update a single subelement contained within an array in a mongodb document. I want to reference the field using its array index (elements within the array don't have any fields that I can guarantee will be unique identifiers). Seems like this should be easy to do, but I can't figure out the syntax.



      Here's what I want to do in pseudo-json.



      Before:



      {
      _id : ...,
      other_stuff ... ,
      my_array : [
      { ... old content A ... },
      { ... old content B ... },
      { ... old content C ... }
      ]
      }


      After:



      {
      _id : ...,
      other_stuff ... ,
      my_array : [
      { ... old content A ... },
      { ... NEW content B ... },
      { ... old content C ... }
      ]
      }


      Seems like the query should be something like this:



      //pseudocode
      db.my_collection.update(
      {_id: ObjectId(document_id), my_array.1 : 1 },
      {my_array.$.content: NEW content B }
      )


      But this doesn't work. I've spent way too long searching the mongodb docs, and trying different variations on this syntax (e.g. using $slice, etc.). I can't find any clear explanation of how to accomplish this kind of update in MongoDB.







      arrays mongodb






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 12 '17 at 17:18









      Massimiliano Kraus

      2,39441633




      2,39441633










      asked Jul 7 '12 at 3:39









      AbeAbe

      6,759146197




      6,759146197
























          4 Answers
          4






          active

          oldest

          votes


















          62














          As expected, the query is easy once you know how. Here's the syntax, in python:



          db["my_collection"].update(
          { "_id": ObjectId(document_id) },
          { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
          )





          share|improve this answer



















          • 2





            where is this documented?

            – ROROROOROROR
            May 14 '18 at 3:49



















          29














          Update of an array element referenced by an index (e.g. 1 ) in Mongo Shell can also be done by directly indicating the index value:



          db.my_collection.update(
          {_id : "document_id"},
          {$set : {"my_array.1.content" : "New content B"}}
          )





          share|improve this answer

































            18














            In mongo style, using '$' positional operator.
            Check out this link for details.



            db.my_collection.update(
            {_id: ObjectId(document_id), my_array.1 : 1 },
            { $set: { "my_array.$.content" : "NEW content B" } }
            )





            share|improve this answer

































              5














              db.my_collection.update(
              {_id: ObjectId(document_id), my_array : { ... old content A ... } },
              { $set: { "my_array.$.content" : "NEW content B" } }
              )





              share|improve this answer
























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11372065%2fmongodb-how-do-i-update-a-single-subelement-in-an-array-referenced-by-the-inde%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                62














                As expected, the query is easy once you know how. Here's the syntax, in python:



                db["my_collection"].update(
                { "_id": ObjectId(document_id) },
                { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
                )





                share|improve this answer



















                • 2





                  where is this documented?

                  – ROROROOROROR
                  May 14 '18 at 3:49
















                62














                As expected, the query is easy once you know how. Here's the syntax, in python:



                db["my_collection"].update(
                { "_id": ObjectId(document_id) },
                { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
                )





                share|improve this answer



















                • 2





                  where is this documented?

                  – ROROROOROROR
                  May 14 '18 at 3:49














                62












                62








                62







                As expected, the query is easy once you know how. Here's the syntax, in python:



                db["my_collection"].update(
                { "_id": ObjectId(document_id) },
                { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
                )





                share|improve this answer













                As expected, the query is easy once you know how. Here's the syntax, in python:



                db["my_collection"].update(
                { "_id": ObjectId(document_id) },
                { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
                )






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jul 7 '12 at 14:29









                AbeAbe

                6,759146197




                6,759146197








                • 2





                  where is this documented?

                  – ROROROOROROR
                  May 14 '18 at 3:49














                • 2





                  where is this documented?

                  – ROROROOROROR
                  May 14 '18 at 3:49








                2




                2





                where is this documented?

                – ROROROOROROR
                May 14 '18 at 3:49





                where is this documented?

                – ROROROOROROR
                May 14 '18 at 3:49













                29














                Update of an array element referenced by an index (e.g. 1 ) in Mongo Shell can also be done by directly indicating the index value:



                db.my_collection.update(
                {_id : "document_id"},
                {$set : {"my_array.1.content" : "New content B"}}
                )





                share|improve this answer






























                  29














                  Update of an array element referenced by an index (e.g. 1 ) in Mongo Shell can also be done by directly indicating the index value:



                  db.my_collection.update(
                  {_id : "document_id"},
                  {$set : {"my_array.1.content" : "New content B"}}
                  )





                  share|improve this answer




























                    29












                    29








                    29







                    Update of an array element referenced by an index (e.g. 1 ) in Mongo Shell can also be done by directly indicating the index value:



                    db.my_collection.update(
                    {_id : "document_id"},
                    {$set : {"my_array.1.content" : "New content B"}}
                    )





                    share|improve this answer















                    Update of an array element referenced by an index (e.g. 1 ) in Mongo Shell can also be done by directly indicating the index value:



                    db.my_collection.update(
                    {_id : "document_id"},
                    {$set : {"my_array.1.content" : "New content B"}}
                    )






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Sep 12 '17 at 17:19









                    Massimiliano Kraus

                    2,39441633




                    2,39441633










                    answered Dec 9 '15 at 11:40









                    tomaskazemekastomaskazemekas

                    2,34722129




                    2,34722129























                        18














                        In mongo style, using '$' positional operator.
                        Check out this link for details.



                        db.my_collection.update(
                        {_id: ObjectId(document_id), my_array.1 : 1 },
                        { $set: { "my_array.$.content" : "NEW content B" } }
                        )





                        share|improve this answer






























                          18














                          In mongo style, using '$' positional operator.
                          Check out this link for details.



                          db.my_collection.update(
                          {_id: ObjectId(document_id), my_array.1 : 1 },
                          { $set: { "my_array.$.content" : "NEW content B" } }
                          )





                          share|improve this answer




























                            18












                            18








                            18







                            In mongo style, using '$' positional operator.
                            Check out this link for details.



                            db.my_collection.update(
                            {_id: ObjectId(document_id), my_array.1 : 1 },
                            { $set: { "my_array.$.content" : "NEW content B" } }
                            )





                            share|improve this answer















                            In mongo style, using '$' positional operator.
                            Check out this link for details.



                            db.my_collection.update(
                            {_id: ObjectId(document_id), my_array.1 : 1 },
                            { $set: { "my_array.$.content" : "NEW content B" } }
                            )






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Aug 13 '17 at 15:12









                            ThisClark

                            8,42874868




                            8,42874868










                            answered May 5 '15 at 17:03









                            DoelDoel

                            427412




                            427412























                                5














                                db.my_collection.update(
                                {_id: ObjectId(document_id), my_array : { ... old content A ... } },
                                { $set: { "my_array.$.content" : "NEW content B" } }
                                )





                                share|improve this answer




























                                  5














                                  db.my_collection.update(
                                  {_id: ObjectId(document_id), my_array : { ... old content A ... } },
                                  { $set: { "my_array.$.content" : "NEW content B" } }
                                  )





                                  share|improve this answer


























                                    5












                                    5








                                    5







                                    db.my_collection.update(
                                    {_id: ObjectId(document_id), my_array : { ... old content A ... } },
                                    { $set: { "my_array.$.content" : "NEW content B" } }
                                    )





                                    share|improve this answer













                                    db.my_collection.update(
                                    {_id: ObjectId(document_id), my_array : { ... old content A ... } },
                                    { $set: { "my_array.$.content" : "NEW content B" } }
                                    )






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jul 21 '17 at 10:48









                                    znbwoznbwo

                                    5111




                                    5111






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11372065%2fmongodb-how-do-i-update-a-single-subelement-in-an-array-referenced-by-the-inde%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        How to change which sound is reproduced for terminal bell?

                                        Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                                        Can I use Tabulator js library in my java Spring + Thymeleaf project?