douqulv6059 2017-03-02 11:51 采纳率: 0%
浏览 976
已采纳

Go中的MongoDB与mgo,带有bson.M / bson.D的运算符始终出现语法错误

It is kind of stupid syntax error, tried tons of ways, just couldn't get it work, someone please help.

MongoDB in Go with mgo, I just tried to simplify use the $ne operator, code like below, but kept getting compile syntax error:

line 15: convIter := Session.Copy().DB("").C("convs").Find(bson.M {
line 16:   "conversationStatus": interface{} {
line 17:     bson.M {
line 18:       "$ne": "DESTROYED"
line 19:     },
line 20:   },
line 21: }).Iter()

Tried to add comma , remove comma everywhere, just couldn't get it work, always got such compile syntax error like below:

mongodb/query.go:16: syntax error: unexpected {, expecting comma or }
mongodb/query.go:20: syntax error: unexpected }, expecting expression
mongodb/query.go:21: syntax error: unexpected }, expecting expression
  • 写回答

1条回答 默认 最新

  • dq62957 2017-03-02 11:55
    关注

    bson.M is a map type, so the bson.M{ ... } is a map literal. If key-value pairs are written in multiple rows, each has to end with a comma. For details, see How to break a long line of code in Golang?

    Also there is no "interface" literal, drop that. A value of interface{} type can hold / wrap any value, including a bson.M value. And the interface{} value creation is automatic, you don't even need a type conversion.

    Correct syntax:

    convIter := Session.Copy().DB("").C("convs").Find(bson.M{
        "conversationStatus": bson.M{
            "$ne": "DESTROYED",
        },
    }).Iter()
    

    Similarly, if you use the bson.D type (which is a slice), lines not ending with the closing bracket of the literal has to end with a comma, e.g.:

    d := bson.D{
        {Name: "fieldA", Value: 1},
        {Name: "fieldB", Value: "running"},
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号