How to update a MongoDB collection with values ​​from another collection?

I have a MongoDB collection called properties and another set of new data in the collection called newProperties .

I want to update one field (amountOwed) in properties with a new value in newProperties for all records where saleNumber is the same in both tables.

I can write one update script when I hard code the values. I can't get the script update to work when using an array, and then parse it with a forEach loop. Can someone explain how to do this?

So, I start with a collection called properties , which looks like this (I only include the relevant fields):

 { "_id" : ObjectId("551816b02eecf1238b3baadb"), "saleNumber" : NumberInt(17917), "saleDetails" : { "amountOwed" : 266.0, } } { "_id" : ObjectId("551816b02eecf1238b3baadc"), "saleNumber" : NumberInt(851400070), "saleDetails" : { "amountOwed" : 270.0, } } 

I am importing a new collection called newProperties that looks like this (note that the number of records has changed for the record using saleNumber 17917):

 { "_id" : ObjectId("551816b02eecf1238b3baadb"), "saleNumber" : NumberInt(17917), "saleDetails" : { "amountOwed" : 300.0, } } 

I want to update properties.saleDetails.amountOwed with a value from newProperties.saleDetails.amountOwed where saleNumbers match.

Here is the query I wrote:

 newActiveProperties.forEach(function(doc) { db.properties.update( { "saleNumber": doc.saleNumber , "auction": ObjectId("56fbf3a8d4c6fe5d73af67c9") }, { $set: { "saleDetails.amountOwed": doc.saleDetails.amountOwed} }, { multi: true }); }); 

When it starts, nothing happens. There are no results in the results tab (I use Mongo Chef), and none of the entries are updated.

I can make it work if I hard code the saleNumber and amountOwed:

 db.properties.update( { "saleNumber": "17917" , "auction": ObjectId("56fbf3a8d4c6fe5d73af67c9") }, { $set: { "saleDetails.amountOwed": 2000} }, { multi: true }); 

I assume this has something to do with the syntax inside the foreach loop, but I'm not sure what it is. Can someone explain how to do this?

+5
source share

Source: https://habr.com/ru/post/1247886/


All Articles