MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

MongoDB, SQL, Access common base abstract class C#

Good morning,
given that I have no extensive knowledge of databases, I was asked to develop a generic MongoDB class derived from an abstract Database class and implement the “Insert”, “Select”, “Update” and “Delete” methods for MongoDB using SQL syntax as input. I am having difficulty converting queries like this

SELECT auto,Part,Entity_ID,Pos_Z 
FROM Nesting 
WHERE Part='033TRAVERSOLATERALE3' or (Part='033TRAVERSOLATERALE1' and Pos_Z=-90)
ORDER BY Pos_Z ASC, Entity_ID DESC

to MongoDB, also with the help of the Aggregation Framework. Can anyone tell me if there is a nuget package or snippet code that already does the query conversion? I found some useful tools but no libraries or sources. Is there no other way than to parsify the SQL WHERE argument string to convert the query?

Part='033TRAVERSOLATERALE3' or (Part='033TRAVERSOLATERALE1' and Pos_Z=-90)

to a MongoDB $match stage with this argument:

{
$or:[{Part: {$eq:'033TRAVERSOLATERALE3'}}, {$and:[{Part: {$eq:'033TRAVERSOLATERALE1'}}, {Pos_Z: {$eq:-90}}]}]
}

or to

BsonDocument filter = new BsonDocument();
            filter.Add("$or", new BsonArray()
                    .Add(new BsonDocument()
                            .Add("Part", "033TRAVERSOLATERALE3")
                    )
                    .Add(new BsonDocument()
                            .Add("$and", new BsonArray()
                                    .Add(new BsonDocument()
                                            .Add("Part", "033TRAVERSOLATERALE1")
                                    )
                                    .Add(new BsonDocument()
                                            .Add("Pos_Z", new BsonInt64(-90L))
                                    )
                            )
                    )
            );

The natural way would perhaps be to use sql-linq and entities but how to do it without defining an a priori entity and creating a class that allows you to perform CRUD operations on any table (e.g. document)?
Any help for this “dirty” job will be greatly appreciated. Thank you

Hi @Pierdomenico_D_Erric, welcome!

Without knowing exactly why you’re trying to develop the class, generally, if you would like a database abstraction in C# you would use LINQ. The code then will have some portability layer. For example see MongoDB .NET/C#: LINQ CRUD. I understand that you would have to create entities for it first, but should work for both SQL and MongoDB.

Regards,
Wan.