MongoDB 仅当光标有字段时才更新字段

MongoDB update field only if cursor has field

我正在使用游标循环更新 MongoDB 文档。但是在下面的查询中,游标 owner 字段不能存在于结果中。我正在使用下面的查询,但看起来 results.hasOwnProperty('owner') 总是返回 true 并且它抛出错误 results.owner doesn't exists.

即使我尝试了 db.contact_coolection.find({"_id" : ObjectId("5b876144d87b4d06ecb571b8")}) --> 这给出了 ownerCRMContactId。$cond 无效。

我认为 $cond 是聚合器运算符,在这种情况下应该使用什么?

db.contact_coolection.find().forEach(function(results)
{    
    print( "Id: " + results._id);
    db.contact_coolection.update( {_id : results._id},
    {$set : {
        "ownerCRMContactId": {
                 $cond: { if: results.hasOwnProperty('owner'), then: results.owner.$id, else: '' }
               }
        }
     });
});

下面是不包含所有者的示例文档

{
    "_id" : ObjectId("5b876144d87b4d06ecb571b8"),
    "_class" : "com.cfcf.crm.model.auth.CRMContact",
    "crmId" : -09898,
    "prefix" : "Mr",
    "firstName" : "fghh",
    "middleName" : "asdgasd",
    "lastName" : "asdasd",
    "suffix" : "asdassd",
    "nickName" : "asdasd",
    "gender" : "Male",
    "age" : "0",
    "dlNumber" : "0",
    "height" : 0,
    "weight" : 0,
    "isSmoker" : false,
    "deleted" : false,
    "isEnabled" : false,
    "externalSource" : [],
    "familyMembers" : [],
    "crmInfos" : [ 
        {
            "opportunityId" : "5b95fa6c28e76b60c0454a2e"
        }
    ],
    "createdDate" : ISODate("2018-08-30T03:15:16.181Z"),
    "lastModifiedDate" : ISODate("2018-09-10T05:00:28.627Z"),
    "createdBy" : "5b2f43e433d58d3e0cd15304",
    "lastModifiedBy" : "5b2f43e433d58d3e0cd15304",
    "owner" : {
        "$ref" : "contact_coolection",
        "$id" : ObjectId("5b2f43e433d58d3e0cd15303")
    },
    "roles" : [],
    "links" : [ 
        {
            "linkId" : 0,
            "linkTitle" : "testsLinkss",
            "linkUrl" : "www.google.com"
        }
    ],
    "addresses" : [ 
        {
            "addressLine1" : "3rd Cross",
            "addressLine2" : "Kensington Street",
            "city" : "Birmingham",
            "state" : "Alabama",
            "country" : "US"
        }
    ]
}

你可以这样做

const promises = db.contact_coolection.find().forEach(async(results) => {
  print( "Id: " + results._id);
  await db.contact_coolection.update(
    { _id: results._id },
    { $set: {
      ownerCRMContactId: results.owner ? results.owner.$id : ''
    }}
  )
})

await Promise.all(promises)

更新

const promises = db.contact_coolection.find().forEach(async(results) => {
  print( "Id: " + results._id);
  await db.contact_coolection.update(
    { _id: results._id },
    { $set: {
      ownerCRMContactId: (results && results.owner) ? results.owner.$id : ''
    }}
  )
})

await Promise.all(promises)