mongoose mongodb交叉集合更新object_id

ymdaylpp  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(133)

我正在尝试更新交叉集合更新,例如
我有两个集合,一个集合名为users,另一个集合名为user_businesses。下面是两个集合的样本数据。
用户集合数据:

{

_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_business集合数据:

{

_id: ObjectId("64a6b0f5a488ab4bc843d331"),

id: 31,

business_id: 196,

contact_person: '',

phone_code: 1,

phone_iso: 'us',

我想更新userscollection**_id:ObjectId(“64a6b0f5af3af7f59a05ba33”)user_businessescollectionbusinesses_id列(充当外键 *),基于where conditionusers.id=user_businesses. businesses_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: ObjectId } }

);

}

});
6fe3ivhb

6fe3ivhb1#

下面的代码片段应该根据条件users.id = user_businesses.business_id使用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 } }
    );
  }
});

相关问题