Home > Net >  Golang Mongo $in filter query throwing an error, (BadValue) unknown top level operator: $in
Golang Mongo $in filter query throwing an error, (BadValue) unknown top level operator: $in

Time:04-24

I am trying to fetch the details from the MongoDB where value of a particular attribute is either a or b. For example, In my collection Test(Attr_A, Attr_B, Attr_C) get the record where value of Attr_C is either "x" or "y".

Filter Query:

filter := bson.M{"Attr_A": "123", "Attr_B": "456",
        "$in": bson.A{bson.D{{"Attr_C", "x"}},
            bson.D{{"Attr_C", "y"}}}}
result := repo.DBPlug.Get("Test", filter)

Error I am getting is,

(BadValue) unknown top level operator: $in. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.

CodePudding user response:

You should specify the field name for the $in operation. Since the JSON filter query should look like:

find({"Attr_A": "123", "Attr_B": "456", "Attr_C": {$in: ["x","y"]}})

I guess in BSON it should be something like:

filter := bson.M{"Attr_A": "123", "Attr_B": "456",
        "Attr_C": bson.M{"$in": bson.A{"x","y"}}}

or something like:

filter := bson.M{"Attr_A": "123", "Attr_B": "456",
          bson.D{{"Attr_C", bson.D{{"$in", bson.A{"x","y"}}}}}
          }

or:

filter := bson.D{{"Attr_A": "123"}, {"Attr_B": "456"},
            {bson.D{{"Attr_C", bson.D{{"$in", bson.A{"x","y"}}}
            }}
          }}

Since this is a filter, the use of bson.M or bson.D is according to your choice - there is no difference in this case. See elaboration

CodePudding user response:

In pure JSON format your filter query would be:

{
    "Attr_A": "123", 
    "Attr_B": "456",
    "Attr_C": {
        "$in": ["x", "y", "z"],
    },
}

Simply translating this to bson, you get

filter := bson.M{
    "Attr_A": "123", 
    "Attr_B": "456",
    "Attr_C": bson.M{
        "$in": bson.A{"x", "y", "z"},
    },
}
result := repo.DBPlug.Get("Test", filter)
  • Related