E
E
Egor Zhivagin2017-06-14 15:46:05
MongoDB
Egor Zhivagin, 2017-06-14 15:46:05

How in Monge to write the value of an object's property to another property of the same object?

Strange title, I'll explain now. I have an object -

{
  name: 'qwerty',
  nameToo: '12345'
}

How do I write the value from nameToo to name ?
I tried with this, but it, logically, points to the wrong thing:
db.getCollection('collection').update({nameToo: {$exists:1}},{$set: {name: this.nameToo}}, {multi:true})

name: undefined

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor Zhivagin, 2017-06-14
@Krasnodar_etc

I don’t hear an answer, I also had to look for Pts for a long time in Google, I’ll write here, all of a sudden someone needs it)

db.getCollection('collection').find({
                nameToo: {$exists:1}
                }).forEach(
    function (elem) {
        db.getCollection('collection').update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.nameToo
                }
            }
        );
    }
);

I say right away that if you have 10,000+ such objects in the database, the script will not run quickly.
It gave me an incomprehensible error, but it worked on almost all objects. I had to replace all the necessary objects with a random
one through the usual one , and then in the script above, make a selection in this already . Then everything is fine. updatenamefindname

E
emp1re, 2017-06-14
@emp1re

$lookup + $out in aggregation pipe line is the
first thing that comes to mind if you want to do it in 1 query.
In general, combinations of operators depend on the difference between documents and the result you want to achieve. But the variations are practically unlimited.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question