Search code examples
c#mongodbprojection

MongoDB Exclude key C# using Criteria


So, i'm been using this Object

public class OrdenCompra
    {
        public String Proveedor { get; set; }
        public String EmitidaPor { get; set; }
        public String NumOrden { get; set; }
        public String TipoPago { get; set; }
        public String Descuento { get; set; }
        public String Recargo { get; set; }
        public String Observacion { get; set; }
        public List<DetalleOrden> Detalle { get; set; }

        public ObjectId Id { get; set; }
        public OrdenCompra() { this.Id = ObjectId.GenerateNewId(); }
        public OrdenCompra(ObjectId id) { this.Id = id; }
    }

I can use the regular Object and there is no problem in my app, but i need to export all the data to a html file, like a report.

Make a html markup and use jQuery to put all the data in a json file to the html.

And i just call it using the regular way

public String JsongetOrdenCompra(String orden)
        {
            try
            {
                return this._Collection.FindOneAs<OrdenCompra>(Query.EQ("NumOrden", orden)).ToJson();
            }
            catch (Exception e)
            {
                throw new Exception("Error al obtener Orden de Compra. \n"+e.Message);
            }
        }

The problem is the "_id" key, so the json looks like

{"key":"value", "bla":"bla", "_id" : ObjectId("516d3f86a3e2c814ac7ca180")}

So i can't parse it ...

I know there is the SetFields(Exclude("_id")) way, but i can't use with the FindOneAs ...

Thanks !


Solution

  • Ending up using C# DataContractJsonSerializer

    First, add using System.Runtime.Serialization; to your class (and project).

    Then add [DataMember] to all your attributes like

    [DataMember]
    public String Proveedor { get; set; }
    [DataMember]
    public String EmitidaPor { get; set; }
    //and so on
    

    Now on your controller

    ClasesProClean.OrdenCompra Orden = HO.getOrdenCompra(orden);
    DataContractJsonSerializer serializer =  new DataContractJsonSerializer(Orden.GetType());
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    serializer.WriteObject(ms, Orden);
    String json = Encoding.Default.GetString(ms.ToArray());
    

    Output:

    {"Descuento":"5%","Detalle":[{"Cantidad":60,"CodProveedor":"45AB","Precio":600,"Producto":"Betún","Total":36000},{"Cantidad":1000,"CodProveedor":"3D2","Precio":1000,"Producto":"Cera para piso flotante","Total":1000000}],"EmitidaPor":"Mario Cares","Id":{"_increment":8167808,"_machine":10740424,"_pid":5292,"_timestamp":1366114182},"NumOrden":"45","Observacion":"A la brevedad","Proveedor":"Atilio Di Gianmmarino S.","Recargo":"10%","TipoPago":"Contado"}
    

    And that is what i was looking for, a readable json ;)