Reputation: 3
I have two collections of addresses. Collection #1 contains names and the address of customers as well as a unique identifier.
Collection #2 contains the same said unique identifier and the customer's telephone number.
Collection #2 with the telephone number is smaller than Collection #1.
What I want to do now is have MongoDB add the telephone number from Collection #2 to the matching documents in Collection #1 only if the unique identifier matches as well. Otherwise it should just skip the document and go over to the next one. In the end I need collection #2 with the added telephone number or no number if it just wasn't there.
Is there an easy way to do this at all?
Upvotes: 0
Views: 42
Reputation: 56
There are two ways you can approach this problem:
If you are using mongoDB version 3.2 and further you can use the $lookup aggregation.
db.address1.aggregate([
{
$lookup:
{
from: "address2",
localField: "unique_field_name",
foreignField: "unique_field_name",
as: "telephone"
}
}])
Running this aggregation will add to address1 the matching document from address2 as an embedded document. It will add this embedded document to all documents in address1 even if there is no matching document in address2.
The second option is to run the following script:
db.address2.find().forEach(
function(address2){
var doc = db.address1.findOne({"unique_identifier":address2.unique_identifier})
db.address1.update({_id: doc._id}, {$set: {telephone: address2. telephone}})
})
Upvotes: 4