简体   繁体   中英

Mongo Query: Copy field+value from one document to another

I cant find an efficient solution for my query. Here is what I'd like to do.

I have a collection called "releases" I have a collection called "tracks"

"releases" has the field "releaseDate", which is filled for every "releases" document.

I now would like to have the corresponding releaseDate of "releases" in every "tracks" document under db.tracks.releases.releaseDate (db.tracks.releases exists already, but without the releaseDate).

To find the corresponding releaseDate, "releases" and "tracks" both have an ICPN number:

db.releases.icpn db.tracks.releases.icpn

Those can be compared to find the correct releaseDate for every track.

To summarize it: I need to go through every track, look at the ICPN, search for the release with the same ICPN und copy the releaseDate from the release to the track.

I could only make it work like this:

db.releases.find().forEach(function(doc) {

db.tracks.update(   


                { "releases.0.ICPN" : doc.ICPN},
                {
                    $set: { "releases.0.releaseDate": doc.releaseDate},
                    $currentDate: {"lastModified": true}
                },
                { multi: true}

            )    

})

That worked for my test DB, but it is ultra inefficient to go through every track for every single release.

Do you have any hints to get me on the right track?

Kind regards, Alex

Currently that query only finds docs where the first element in releases is ICPN

You want to query without an absolute index like:

{ "releases.ICPN" : doc.ICPN}

and update with the positional operator so it updates the one it found to match:

$set: { "releases.$.releaseDate": doc.releaseDate},

好了,查询现在部分起作用了,但是在我编辑了1700个音轨(共160000个)后它停止了,尽管我将multi设置为true,并且所有其他音轨/发行版的条件都是true(如果ICPN匹配,我会手动检查一些未修改的音轨)​​。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM