Search code examples
mongodbgobsonmgo

MongoDB in Go with mgo, operators with bson.M / bson.D always got syntax error


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

Solution

  • 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"},
    }