Mongo 数据库更新

苏尼尔

我是 mongo 的新手,我正在寻求帮助。

MongoDB Enterprise > db.servmon.find({ "hostName" : “server-prf-004”})   
{ "_id" : ObjectId("58f0a4a2ff980d97cce0a79c"), "hostName" : “server-prf-004", "thresholds" : [ { "warn" : "None", "crit" : "None", "contact_mail" : "None", "type" : "loadcheck", "contact_page" : "None" }, { "warn" : "None", "crit" : "None", "contact_mail" : "None", "type" : "mu_check", "contact_page" : "None" }, { "map" : "/ora,/arch", "crit" : "None", "warn" : "None", "contact_mail" : "None", "type" : "diskmon", "contact_page" : "None" } ] }

如果我只想更改数据库中的一项

{ "warn" : "None", "crit" : "None", "contact_mail" : "None", "type" : "loadcheck", "contact_page" : "None” } to  to { "warn" : “90", "crit" : “80", "contact_mail" : "None", "type" : "loadcheck", "contact_page" : "None” }

最好的选择是什么?

我尝试使用 update 和 findModify,但它正在更新阈值后的所有条目,如下所示:

MongoDB Enterprise > db.servmon.findAndModify ( { query:{"hostName" : “server-prf-004","thresholds" : { "warn" : "None", "crit" : "None", "contact_mail" : "None", "type" : "mu_check", "contact_page" : "None" } }, update :{ "hostName" : "server-prf-002","thresholds" : { "warn" : "80", "crit" : "90", "contact_mail" : "None", "type" : "mu_check", "contact_page" : "None" }  } ,upsert: true } )

MongoDB Enterprise > db.servmon.find({ "hostName" : “server-prf-004"})
{ "_id" : ObjectId("58f0a4a2ff980d97cce0a799"), "hostName" : "server-prf-001", "thresholds" : { "warn" : "80", "crit" : "90", "contact_mail" : "None", "type" : "mu_check", "contact_page" : "None" } }
MongoDB Enterprise >
s7vr

执行所选文档的更新。更新字段使用相同的更新操作符或字段:值规范来修改所选文档。

update() 方法要么修改现有文档中的特定字段,要么完全替换现有文档。

您正在使用完全替换文档的更新变体。

您需要的是更新变体,它使用更新运算符来有选择地更新字段。

就像是

db.servmon.findAndModify ( { query:{"hostName" : "server-prf-004", "thresholds" : { "warn" : "None", "crit" : "None", "contact_mail" : "None", "type" : "mu_check", "contact_page" : "None" } }, update :{ $set:{ "hostName" : "server-prf-002", "thresholds.$" : { "warn" : "80", "crit" : "90", "contact_mail" : "None", "type" : "mu_check", "contact_page" : "None" } } } ,upsert: true } )

注意:$set是一个更新操作符,它使用位置操作符更新hostnamethresholds.$更新所选数组从查询到更新值。

https://docs.mongodb.com/manual/reference/command/findAndModify/#dbcmd.findAndModify

https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-parameter

https://docs.mongodb.com/manual/reference/operator/update/set/#up._S_set

https://docs.mongodb.com/manual/reference/operator/update/positional/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章