我正在使用游标循环更新MongoDB文档。但是在下面的查询光标 owner 字段中不能存在结果。我正在使用下面的查询,但看起来像是result.hasOwnProperty('owner')始终返回true,并且抛出错误结果。owner不存在。
即使我尝试了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"
}
]
}
答案 0 :(得分:2)
您可以这样做
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)