无法使用golang

时间:2018-08-14 21:22:09

标签: mongodb go

我正在使用mgo在golang中使用mongo查询来更新子元素属性

 {
        "_id" : ObjectId("5b64a0d3931653c36bcaf0b5"),
        "quantity" : 2,
        "product" : "ABC",   
        "children" : [ 
            {     "jiraId":"100"      
                "isBlocked" : true,
                "blockedMessage" : "Error occurred: TRACEID",
                "serialNo" : "abc123",
                "token" : "",            
            }
        ]
    }

我在下面使用的查询

Update(repository.MongoSpec{Selector: bson.M{"children": bson.M{"$elemMatch": bson.M{"jid": "100"}}}, Query: bson.M{"children": bson.M{"$set": fields}}})

下面是更新功能

    s := spec.(MongoSpec).Selector
q := spec.(MongoSpec).Query
err := session.
    DB(repo.config.databaseName).
    C(repo.collectionName).
    Update(s, q)

MongoSpec结构

  type MongoSpec struct {
        Selector interface{}
        Query    interface{}
    }

上面的查询抛出如下错误

The dollar ($) prefixed field '$set' in 'children.$set' is not valid for storage.

我可以知道查询出了什么问题吗

2 个答案:

答案 0 :(得分:1)

  

Update(repository.MongoSpec {选择器:bson.M {“儿童”:bson.M {“ $ elemMatch”:bson.M {“ jid”:“ 100”}}}},查询:bson.M {“ children“:bson.M {” $ set“:fields}}})

如果在$elemMatch表达式中仅指定单个查询条件,则无需使用$elemMatch。只需使用dot notation即可访问数组或嵌入式文档的元素。例如在mongo shell中:

db.collection.update(
      {"children.jid": "100"}, 
      {"$set":{"children.$.field":"foobar"}})

请注意,首先在任何字段之前指定更新操作符$set。另请参见Set Fields in Embedded Documents

此外,请注意数组字段$children之间的附加field。这是positional $ operator,用于标识要更新的数组元素,而无需显式指定该元素在数组中的位置。例如,如果您在children中有两个元素,则仅将update运算符应用于与jid="100"匹配的元素。

类似地使用mgo.v2,您可以指定:

err = c.Update(
         bson.M{"children.jid":"100"}, 
         bson.M{"$set":bson.M{"children.$.field":"foobar"}}
      )

值得一提的是,mgo.v2已停产,如果您要开始一个新项目,请使用mongo-go-driver支持MongoDB v3.2及更高版本。

答案 1 :(得分:0)

我认为您没有正确使用$ set,请检查此示例并使其适应您的语言:

getCollection('collectionName').findOneAndUpdate(
   {"children.jiraId":100}, //Search the subdocument
   {$set:{"children.$.isBloqued":false}}}, //update the subdocument
)