Query if a field exist or is null from Golang

Hi Guys, im trying to query mongodb documents (from Go) if a certain column does not exist or if the column value is null, so far with the query i have it only return rows where the column does not exist and leaves out rows where the value is null. here is what i have for the filter:

bson.D{{"$or", []interface{}{
    bson.D{{"date", bson.M{"$eq": bsontype.Null}}},
    bson.D{{"date", bson.M{"$exists": false}}},
},

this query does not give any errors, it just returns only rows where the date column does not exist, leaving out those where it exists and the value is null. does anyone have an idea of how to achieve this in Go? all response is appreciated. thanks…

1 Like

You could use the nil type check which is a built-in datatype in golang.

bson.D{{"$or", []interface{}{
    bson.D{{"date", nil}},
    bson.D{{"date", bson.M{"$exists": false}}},
},

Note: By default, MongoDB considers keys that don’t exist in a document as null

Therefore the below query will also work for your scenario.

findQry := bson.D{{"date", nil}}   // will fetch documents if the key doesn't exist too in addition to null