Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongodb cross collection update object_id

I am trying to update cross collection update, for example

I have two collections, One collection name is users and another collection name is user_businesses. Below is the sample data of both the collections.

user collection data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {

_id: ObjectId("64a6b0f5af3af7f59a05ba33"),

id: 134,

display_id: 'PRM-SRL-000001348',

client_emp_code: '',

entity_code: '',

user_type: 'candidate',

role: '',

user_account_type: '',

business_id: 104,

parent_id: 94,

user_businesses collection data:

    {

_id: ObjectId("64a6b0f5a488ab4bc843d331"),

id: 31,

business_id: 196,

contact_person: '',

phone_code: 1,

phone_iso: 'us',

I want to update users collection _id: ObjectId("64a6b0f5af3af7f59a05ba33") to user_businesses collection business_id column (act as a foreign key) based on where condition users.id=user_businesses.business_id.

I have used below code, the code executed successfully, But values are not updated. Please someone correct me the code if i am wrong.

    db.users.find().forEach(function(userDoc) {

var matchingBusinessDoc = db.user_businesses.findOne({ business_id: userDoc.id });

if (matchingBusinessDoc) {

db.user_businesses.updateOne(

{ business_id: userDoc.id },

{ $set: { business_id: userDoc._id: ObjectId } }

);

}

});

>Solution :

The snippet below should update the business_id field in the user_businesses collection with the corresponding _id from the users collection based on the condition users.id = user_businesses.business_id.

db.users.find().forEach(function(userDoc) {
  var matchingBusinessDoc = db.user_businesses.findOne({ business_id: userDoc.id });
  if (matchingBusinessDoc) {
    db.user_businesses.updateOne(
      { business_id: userDoc.id },
      { $set: { business_id: userDoc._id } }
    );
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading