我正在尝试将字段追加到mongodb集合中的对象。到目前为止,这就是我在MongoDB中的文档的样子。
我的用户可以有多个设备,所以我试图将更多字段附加到devices对象。我曾尝试将$ push用作数组而不是对象,但我不喜欢以后从数据库中检索数据时如何访问数据。
所以我开始使用$ set。 $ set非常有用,因为它为我提供了我希望数据保存在数据库中的格式,但是每次都将不断覆盖我在devices对象中的一个键值对,而我不希望这种情况发生。
db.go
$ ipython
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.17.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: def test(i):
...: print(i)
...:
In [2]: print(i)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-3b184248ad5a> in <module>
----> 1 print(i)
NameError: name 'i' is not defined
我已经研究过使用$ addFields了,但是我不知道我做得是否正确,我只是替换了上面的$ set并添加了$ addFields,我也尝试过这种方式
func AddDeviceToProfile(uid string, deviceId int, deviceName string) {
client := ConnectClient()
col := client.Database(uid).Collection("User")
idString := strconv.Itoa(deviceId)
filter := bson.M{"uid": uid}
update := bson.M{
"$set": bson.M{"devices": bson.M{idString: deviceName}}, <------ Need to fix this
}
option := options.FindOneAndUpdate()
_ = col.FindOneAndUpdate(context.TODO(), filter, update, option)
log.Print("Device Added")
_ = client.Disconnect(context.TODO())
}
我希望我的文档看起来像什么
答案 0 :(得分:2)
您不需要使用$ push或$ addFields而是$ set指令。
要在嵌入式文档中指定一个字段,请使用点符号。
对于匹配标准_id等于100的文档,以下操作将更新设备文档中的make字段:
db.products.update(
{ _id: 100 },
{ $set: { "devices.make": "zzz" } }
)
将它们转换为Go语法也很容易。你在做什么是正确的。以下应该可行,或者可能需要一些调整。
func AddDeviceToProfile(uid string, deviceId int, deviceName string) {
client := ConnectClient()
col := client.Database(uid).Collection("User")
idString := strconv.Itoa(deviceId)
filter := bson.M{"uid": uid}
update := bson.M{"$set": bson.M{"devices." + idString: deviceName}}
option := options.FindOneAndUpdate()
_ = col.FindOneAndUpdate(context.TODO(), filter, update, option)
log.Print("Device Added")
_ = client.Disconnect(context.TODO())
}