8

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
icza
  • 389,944
  • 63
  • 907
  • 827
lnshi
  • 85
  • 1
  • 1
  • 5

1 Answers1

9

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"},
}
icza
  • 389,944
  • 63
  • 907
  • 827
  • thank u very much for ur super quick answer, yea, it works. – lnshi Mar 02 '17 at 12:00
  • i saw another answer here: http://stackoverflow.com/questions/26932298/mongodb-in-go-golang-with-mgo-how-to-use-logical-operators-to-query , when the filed need to be used with slice, then the answer showed the correct way is: `"$or": []interface{} {bson.M{"key2": 2}, bson.M{"key3": 2},},`, if don't use the `interface` literal, what is the correct way to do that? – lnshi Mar 02 '17 at 12:09
  • 1
    @lnshi When you need to create a _slice_ whose type is `[]interface{}`, then you need to state the slice type in the literal, e.g. `[]interface{}{1, "two"}`. But in your case you're not creating a slice, only a _single value_, of which the `interface{}` value creation is automatic, as stated in the answer. – icza Mar 02 '17 at 12:11