mongodbmongoosemongodb-querymongodb-compass

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:

 {

_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 } }
        );
      }
    });