Update MongoDB field using value of another fieldMongoDB: Updating documents using data from the same documentUpdate field with another field's value in the documentMongoDB : how to set a new field equal to the value of another field, for every document in a collectionMongoose findOneAndUpdate - update one field using anotherHow to update a field using its previous value in MongoDB/MongoosePyMongo - Setting all values in an attribute to lowercaseupdate field with existing field in mongodbUpdate specific field in all documents in MongoDBAdd new field which is the size of another field of the documentmongodb update query to append a data to already existing fieldHow do I perform the SQL Join equivalent in MongoDB?Update field with another field's value in the documentMongoDB vs. CassandraHow to query MongoDB with “like”?Retrieve only the queried element in an object array in MongoDB collectionHow to secure MongoDB with username and passwordHow do I drop a MongoDB database from the command line?MongoDB: update every document on one fieldMySQL vs MongoDB 1000 readsChecking if a field contains a string

Why does the A-4 Skyhawk sit nose-up when on ground?

Why is C++ initial allocation so much larger than C's?

Is it okay to visually align the elements in a logo?

Architecture of networked game engine

Counting occurrence of words in table is slow

Alphabet completion rate

STM Microcontroller burns every time

Is my Rep in Stack-Exchange Form?

How well known and how commonly used was Huffman coding in 1979?

The impact of an intelligent and (mostly) hostile flying race on weapons and armor

Does the Paladin's Aura of Protection affect only either her or ONE ally in range?

Why does adding parentheses prevent an error?

Fedora boot screen shows both Fedora logo and Lenovo logo. Why and How?

Does ultrasonic bath cleaning damage laboratory volumetric glassware calibration?

Why is the Turkish president's surname spelt in Russian as Эрдоган, with г?

Should my manager be aware of private LinkedIn approaches I receive? How to politely have this happen?

How could mana leakage be dangerous to a elf?

How can Charles Proxy change settings without admin rights after first time?

Why does the numerical solution of an ODE move away from an unstable equilibrium?

Was touching your nose a greeting in second millenium Mesopotamia?

Cascading Repair Costs following Blown Head Gasket on a 2004 Subaru Outback

How to determine what is the correct level of detail when modelling?

Does the UK have a written constitution?

How many satellites can stay in a Lagrange point?



Update MongoDB field using value of another field


MongoDB: Updating documents using data from the same documentUpdate field with another field's value in the documentMongoDB : how to set a new field equal to the value of another field, for every document in a collectionMongoose findOneAndUpdate - update one field using anotherHow to update a field using its previous value in MongoDB/MongoosePyMongo - Setting all values in an attribute to lowercaseupdate field with existing field in mongodbUpdate specific field in all documents in MongoDBAdd new field which is the size of another field of the documentmongodb update query to append a data to already existing fieldHow do I perform the SQL Join equivalent in MongoDB?Update field with another field's value in the documentMongoDB vs. CassandraHow to query MongoDB with “like”?Retrieve only the queried element in an object array in MongoDB collectionHow to secure MongoDB with username and passwordHow do I drop a MongoDB database from the command line?MongoDB: update every document on one fieldMySQL vs MongoDB 1000 readsChecking if a field contains a string






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








301















In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like:



UPDATE Person SET Name = FirstName + ' ' + LastName


And the MongoDB pseudo-code would be:



db.person.update( ,  













301















In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like:



UPDATE Person SET Name = FirstName + ' ' + LastName


And the MongoDB pseudo-code would be:



db.person.update( ,  









301












301








301


73






In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like:



UPDATE Person SET Name = FirstName + ' ' + LastName


And the MongoDB pseudo-code would be:



db.person.update( , improve this answer





















    share)





    share)






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Apr 3 '15 at 11:44









    Chris GibbChris Gibb

    5225 silver badges8 bronze badges




    5225 silver badges8 bronze badges







    • 1





      How is this different? Will the steam be throttled by the update activity? Do you have any reference to it? The Mongo docs are quite poor.

      – Nico
      Nov 21 '16 at 14:58












    • 1





      How is this different? Will the steam be throttled by the update activity? Do you have any reference to it? The Mongo docs are quite poor.

      – Nico
      Nov 21 '16 at 14:58







    1




    1





    How is this different? Will the steam be throttled by the update activity? Do you have any reference to it? The Mongo docs are quite poor.

    – Nico
    Nov 21 '16 at 14:58





    How is this different? Will the steam be throttled by the update activity? Do you have any reference to it? The Mongo docs are quite poor.

    – Nico
    Nov 21 '16 at 14:58











    3














    Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:



    db.person.find().forEach(
    function (elem)
    db.person.update(

    _id: elem._id
    ,

    $set:
    name: elem.firstname + ' ' + elem.lastname


    );

    );





    share|improve this answer



























      3














      Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:



      db.person.find().forEach(
      function (elem)
      db.person.update(

      _id: elem._id
      ,

      $set:
      name: elem.firstname + ' ' + elem.lastname


      );

      );





      share|improve this answer

























        3












        3








        3







        Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:



        db.person.find().forEach(
        function (elem)
        db.person.update(

        _id: elem._id
        ,

        $set:
        name: elem.firstname + ' ' + elem.lastname


        );

        );





        share|improve this answer













        Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:



        db.person.find().forEach(
        function (elem)
        db.person.update(

        _id: elem._id
        ,

        $set:
        name: elem.firstname + ' ' + elem.lastname


        );

        );






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 15 at 17:20









        AldoAldo

        4294 silver badges11 bronze badges




        4294 silver badges11 bronze badges





















            2














            Here's what we came up with for copying one field to another for ~150_000 records. It took about 6 minutes, but is still significantly less resource intensive than it would have been to instantiate and iterate over the same number of ruby objects.



            js_query = %(
            $or : [

            'settings.mobile_notifications' : $exists : false ,
            'settings.mobile_admin_notifications' : $exists : false

            ]
            )

            js_for_each = %(function(user)
            if (!user.settings.hasOwnProperty('mobile_notifications'))
            user.settings.mobile_notifications = user.settings.email_notifications;

            if (!user.settings.hasOwnProperty('mobile_admin_notifications'))
            user.settings.mobile_admin_notifications = user.settings.email_admin_notifications;

            db.users.save(user);
            )

            js = "db.users.find(#js_query).forEach(#js_for_each);"
            Mongoid::Sessions.default.command('$eval' => js)





            share|improve this answer



























              2














              Here's what we came up with for copying one field to another for ~150_000 records. It took about 6 minutes, but is still significantly less resource intensive than it would have been to instantiate and iterate over the same number of ruby objects.



              js_query = %(
              $or : [

              'settings.mobile_notifications' : $exists : false ,
              'settings.mobile_admin_notifications' : $exists : false

              ]
              )

              js_for_each = %(function(user)
              if (!user.settings.hasOwnProperty('mobile_notifications'))
              user.settings.mobile_notifications = user.settings.email_notifications;

              if (!user.settings.hasOwnProperty('mobile_admin_notifications'))
              user.settings.mobile_admin_notifications = user.settings.email_admin_notifications;

              db.users.save(user);
              )

              js = "db.users.find(#js_query).forEach(#js_for_each);"
              Mongoid::Sessions.default.command('$eval' => js)





              share|improve this answer

























                2












                2








                2







                Here's what we came up with for copying one field to another for ~150_000 records. It took about 6 minutes, but is still significantly less resource intensive than it would have been to instantiate and iterate over the same number of ruby objects.



                js_query = %(
                $or : [

                'settings.mobile_notifications' : $exists : false ,
                'settings.mobile_admin_notifications' : $exists : false

                ]
                )

                js_for_each = %(function(user)
                if (!user.settings.hasOwnProperty('mobile_notifications'))
                user.settings.mobile_notifications = user.settings.email_notifications;

                if (!user.settings.hasOwnProperty('mobile_admin_notifications'))
                user.settings.mobile_admin_notifications = user.settings.email_admin_notifications;

                db.users.save(user);
                )

                js = "db.users.find(#js_query).forEach(#js_for_each);"
                Mongoid::Sessions.default.command('$eval' => js)





                share|improve this answer













                Here's what we came up with for copying one field to another for ~150_000 records. It took about 6 minutes, but is still significantly less resource intensive than it would have been to instantiate and iterate over the same number of ruby objects.



                js_query = %(
                $or : [

                'settings.mobile_notifications' : $exists : false ,
                'settings.mobile_admin_notifications' : $exists : false

                ]
                )

                js_for_each = %(function(user)
                if (!user.settings.hasOwnProperty('mobile_notifications'))
                user.settings.mobile_notifications = user.settings.email_notifications;

                if (!user.settings.hasOwnProperty('mobile_admin_notifications'))
                user.settings.mobile_admin_notifications = user.settings.email_admin_notifications;

                db.users.save(user);
                )

                js = "db.users.find(#js_query).forEach(#js_for_each);"
                Mongoid::Sessions.default.command('$eval' => js)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jun 8 '16 at 15:07









                Chris BloomChris Bloom

                2,5301 gold badge27 silver badges43 bronze badges




                2,5301 gold badge27 silver badges43 bronze badges





















                    0














                    Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:



                    // firstName: "Hello", lastName: "World" 
                    db.collection.update(
                    ,
                    [ $set: name: $concat: [ "$firstName", " ", "$lastName" ] ],
                    multi: true
                    )
                    // "firstName" : "Hello", "lastName" : "World", "name" : "Hello World"


                    • The first part is the match query, filtering which documents to update (in our case all documents).


                    • The second part [{ $set: name: ... ] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields.


                    • Don't forget multi: true , otherwise only the first matching document will be updated.






                    share|improve this answer





























                      0














                      Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:



                      // firstName: "Hello", lastName: "World" 
                      db.collection.update(
                      ,
                      [ $set: name: $concat: [ "$firstName", " ", "$lastName" ] ],
                      multi: true
                      )
                      // "firstName" : "Hello", "lastName" : "World", "name" : "Hello World"


                      • The first part is the match query, filtering which documents to update (in our case all documents).


                      • The second part [{ $set: name: ... ] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields.


                      • Don't forget multi: true , otherwise only the first matching document will be updated.






                      share|improve this answer



























                        0












                        0








                        0







                        Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:



                        // firstName: "Hello", lastName: "World" 
                        db.collection.update(
                        ,
                        [ $set: name: $concat: [ "$firstName", " ", "$lastName" ] ],
                        multi: true
                        )
                        // "firstName" : "Hello", "lastName" : "World", "name" : "Hello World"


                        • The first part is the match query, filtering which documents to update (in our case all documents).


                        • The second part [{ $set: name: ... ] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields.


                        • Don't forget multi: true , otherwise only the first matching document will be updated.






                        share|improve this answer















                        Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:



                        // firstName: "Hello", lastName: "World" 
                        db.collection.update(
                        ,
                        [ $set: name: $concat: [ "$firstName", " ", "$lastName" ] ],
                        multi: true
                        )
                        // "firstName" : "Hello", "lastName" : "World", "name" : "Hello World"


                        • The first part is the match query, filtering which documents to update (in our case all documents).


                        • The second part [{ $set: name: ... ] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields.


                        • Don't forget multi: true , otherwise only the first matching document will be updated.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jun 11 at 23:03

























                        answered Jun 11 at 20:35









                        Xavier GuihotXavier Guihot

                        10k11 gold badges33 silver badges39 bronze badges




                        10k11 gold badges33 silver badges39 bronze badges



























                            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%2f3974985%2fupdate-mongodb-field-using-value-of-another-field%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

                            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현