mongodb - Mongo DB 更新查询
问题描述
我将以下文档存储在 mongo DB 集合中,我需要添加新订阅者 例如,我需要添加带有“协议”的订阅者:“SOAP”和 url http ://localhost.8080/FNOL/subscriber3文件中的名称 "name" : "FNOL","country" : "US","lob" : "property"。
如果我们添加的 url 已经存在,我们不应该添加到文档中,以防文档不存在匹配条件名称 "name" : "FNOL","country" : "US","lob" : "属性”我需要插入一个新文档。
是否可以在 mongo db 中的单个命令中完成上述所有操作?
提前致谢。
{
"_id" : ObjectId("5b07fbbc0d7a677d2f8b2d87"),
"name" : "FNOL",
"country" : "US",
"lob" : "property",
"subscribers" : [
{
"protocol" : "REST",
"url" : "http://localhost.8080/FNOL/subscriber1"
},
{
"protocol" : "SOAP",
"url" : "http://localhost.8080/FNOL/subscriber2"
},
{
"protocol" : "JMS",
"url" : "NOTIFICATION.TOPIC.FNOL"
}
]
}
更新后:
{
"_id" : ObjectId("5b07fbbc0d7a677d2f8b2d87"),
"name" : "FNOL",
"country" : "US",
"lob" : "property",
"subscribers" : [
{
"protocol" : "SOAP",
"url" : "http://localhost.8080/FNOL/subscriber2"
},
{
"protocol" : "JMS",
"url" : "NOTIFICATION.TOPIC.FNOL"
},
{
"protocol" : "SOAP",
"url" : "http://localhost.8080/FNOL/subscriber2"
}
,
{
"protocol" : "SOAP",
"url" : "http://localhost.8080/FNOL/subscriber3"
}
]
}
解决方案
You need to use $addToSet... It will not push the data if it already exist in the array
db.collection.update(
{ name: 'FNOL', country: 'US', lob: 'property' },
{ $addToSet: { subscribers: { "protocol" : "SOAP", url: 'http://localhost.8080/FNOL/subscriber3' } } },
{ upsert: true }
)
推荐阅读
- c# - 映射没有主索引但具有唯一索引的 Oracle 数据库表
- linux - 如何在 bash 中的 ssh 期望脚本中自动执行 ctrl+d 操作?
- c++ - 绑定到 const 引用的临时对象是否被视为 const 对象?
- mysql - 从表中选择最小值(也是最大值和平均值)以及事件的时间戳
- typescript - 基于现有打字稿的动态类型
- python - 使用数据框获取 xls 数据,并将其发送到 API 帖子
- qt - qt 中使用 drawText() 的文本对齐导致 fnt-font 出错
- rust - 如何处理未知类型
- java - Is there a way to read from specific offset in a Kafka stream from a Spark streaming job?
- python - UnicodeEncodeError: 'latin-1' codec can't encode character u'\u05a0' in position 85: ordinal not in range(256)