0

I have currently a working filter for .DeleteMany. It deletes all entries where _id is in the given array vids:

filter := bson.D{{Key: "_id", Value: bson.D{{Key: "$in", Value: vids}}}}
res, err := DB.Collection("data").DeleteMany(context.TODO(), filter)

Now I want to enhance the filter and add some $and condition to only delete entries where _id is in the given array vids and(!) the value of providerid is 1234.

Sadly I'm stuck on how to do that in go. For me it is extremely hard to read and write such filters. Especially with all that bson.D, bson.M and []bson.D and the many curly brackets etc.

In SQL I would write DELETE FROM data WHERE _id IN( {list} ) AND providerid=1234;

Is there any SQL to golang mongodb filter converter?

1 Answer 1

2

Try

filter := bson.D{
    { "$and", []interface{}{
        bson.D{{ Key: "_id", Value: bson.D{{ Key: "$in", Value: vids }}}},
        bson.D{{ "providerid", 123}},
    }},
}

As per @VolkerSchmid comment

filter := bson.D{ { Key: "$and", Value: []interface{}{ bson.D{{ Key: "_id", Value: bson.D{{ Key: "$in", Value: vids }}}}, bson.D{{ Key: "providerid", Value: 123}}, }}, }
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Tushar, but this triggers "go.mongodb.org/mongo-driver/bson/primitive.E composite literal uses unkeyed fields" in VS Code. To get rid of this, I need to write like this:filter := bson.D{ { Key: "$and", Value: []interface{}{ bson.D{{ Key: "_id", Value: bson.D{{ Key: "$in", Value: vids }}}}, bson.D{{ Key: "providerid", Value: 123}}, }}, } But is there some code generator or such, making it more easy to write such filters?
Strange that mongodb needs us to write 10 opening curly brackets, 10 closing curly brackets and a set of square brackets just for such a simple filter... Some generator would be of great help.
yes, it works after adaption with Key: and Value:. Thanks for this! But the main part of my question was about a SQL to mongodb converter.
Gupta Thank you, this is a good start. But it just generates a mongodb search filter. It still lacks all the golang related things like interface, bson.D etc... It also adds some weird {"E": 1} to the query I dont understand. But only if the query is a DELETE query. But helpful anyway.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.