我尝试在Golang中运行MongoDB查询并收到一些错误。如果字段“section.gateBack”等于0,我想用新的时间戳更新字段“expiresAt”。
数据模型如下所示:
{
"_id": "78b0e7de-c24c-11eb-8529-0242ac130003",
"expiresAt": "2021-04-22T14:06:55.069Z",
"section": {
"gateFront": 1,
"gateMiddle": 1,
"gateBack": 0
}
}
在第一次尝试中,我编写了查询,就像我执行其他(简单)$set操作一样,但这次使用$cond使用if-else:
filter := bson.M{
"_id": iD,
}
update := bson.M{
"$set": bson.M{
"expiresAt": bson.M{
"$cond": bson.M{
"if": bson.M{
"$and": []bson.M{
{"section.gateBack": bson.M{"$eq": 0}},
{"section.gateBack": bson.M{"$exists": true}},
},
},
"then": time.Now().AddDate(0, 1, 0),
"else": time.Now().AddDate(0, 0, 1),
},
},
},
}
res, err := s.coll.UpdateOne(
ctx,
filter,
update,
)
但是使用此更新操作,我得到以下错误:
multiple write errors: [{write errors: [{The dollar ($) prefixed field '$cond' in 'expiresAt.$cond' is not valid for storage.}]}, {<nil>}]
我在MongoDB开发人员方面发现了一个问题,它说更新值必须是一个数组:https://developer.mongodb.com/community/forums/t/mongoerror-the-dollar-prefixed-field-cond-in-energy-cond-is-not-valid-for-storage/16448
当我阅读MongoDB的官方文档时,这是有道理的,用于使用聚合管道的UpdateOne():https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/#example-2
因此,我更改了我的更新值并将其附加到 bson 数组中。M:
filter := bson.M{
"_id": iD,
}
var pipeline []bson.M
update := bson.M{
"$set": bson.M{
"expiresAt": bson.M{
"$cond": bson.M{
"if": bson.M{
"$and": []bson.M{
{"section.gateBack": bson.M{"$eq": 0}},
{"section.gateBack": bson.M{"$exists": true}},
},
},
"then": time.Now().AddDate(0, 1, 0),
"else": time.Now().AddDate(0, 0, 1),
},
},
},
}
pipeline = append(pipeline, update)
res, err := s.coll.UpdateOne(
ctx,
filter,
pipeline,
)
慕桂英4014372
湖上湖
相关分类