在对象数组中插入一个新对象



在MongoDB集合中,我有一个文档,其中包含一个具有各种KV对的对象,用于描述特定的传感器。配置对象的格式如下所示。我想要做的是将新的数组元素添加到配置中,例如rssi,它本身将包含一个对象数组。我还想删除数组中的对象。感觉应该使用$push和$pull操作符。查询正在用golang编码。Sensor_sn可以作为唯一标识符。对如何做到这一点有什么建议吗?

{
"configuration": {
"ta": [
{
"ident": 0,
"description": "Temperature",
"sensor_sn": "828082837284",
"unit": "℃",
"type": "number",
"elemID": "ta0"
},
{
"ident": 1,
"description": "Temperature",
"sensor_sn": "0258c40d0000",
"unit": "℃",
"type": "number",
"elemID": "ta1"
},
{
"ident": 2,
"description": "Temperature",
"sensor_sn": "ed9dc30d0000",
"unit": "℃",
"type": "number",
"elemID": "ta2"
}
],
"rh": [
{
"ident": 0,
"description": "Relative Humidity",
"sensor_sn": "",
"unit": "%",
"type": "number",
"elemID": "rh"
}
],
"vlt2": [
{
"ident": 0,
"description": "Battery Voltage",
"sensor_sn": "",
"unit": "V",
"type": "number",
"elemID": "vlt2"
}
],
"pt": [
{
"ident": 0,
"description": "Precipitation",
"sensor_sn": "",
"unit": "mm/tip",
"type": "number",
"elemID": "pt"
}
]
}
}

我看了看各种论坛,看看我是否能找到一个合适的模式来修改,但到目前为止还没有完全理解如何实现我的目标。https://www.mongodb.com/docs/manual/reference/operator/update/pull/MongoDB -在数组

中更新或插入对象

你看过$addToSet吗?它会在数组中添加一个不存在的值。$pull将从数组中删除匹配项。

对于这两个调用,设置基本相同。我的方法是创建一个bson。M{}的新元素或删除的数组元素,然后创建一个bson。M{}使用字段名和上面定义的更新,最后使用$addToSet或$pull命令和您正在设置的内容创建更新。

假设您正在使用MongoDB Go驱动程序,您可以尝试:

theData := bson.M{"ident": 1, "description": "New item", "sensor_sn": "new sensor", "unit": "V", "type": "number", "elemID": "vlt2"}
whatToChange := bson.M{"configuration.rssi": theData}
To add the element:
update := bson.M{"$addToSet": whatToChange}
To delete it:
update := bson.M{"$pull": whatToChange}
_, err = theCollection.UpdateOne(
context.Background(),
bson.M{"_id": "itemID"},
update,
)

最新更新