How to get the Id of the last record inserted in MongoDB and C #?

1

I'm working with MongoDB and c #, this is the way I insert Data.

My Class Employees

    public class Empleados
    {
        public string Nombre{ get; set; }
        public string Direccion { get; set; }
    }

Button Method

Empleados empleado= new Empleados ();
empleado.Nombre= "Rastalovely";
empleado.Direccion= "Mexico";
Insert_Empleados(empleado);

Private Method

private void Insert_Empleados(Empleados empleado)
    {
        var coleccion = data.GetCollection<BsonDocument>("empleados");
        BsonDocument documento = empleado.ToBsonDocument();
        coleccion.InsertOne(documento);
    }
  

What I need is to get the ID of the last employee added.

    
asked by Rastalovely 13.12.2016 в 22:46
source

2 answers

1

You can try

SortByBuilder sbb = new SortByBuilder();
sbb.Descending("_id");
var ultimo = coleccion.FindAllAs<BsonDocument>().SetSortOrder(sbb).SetLimit(1);

extracted from the question from stack over flow in English

EDIT

var sortBy = SortBy.Descending("_id");
var ultimo = coleccion.FindAs<BsonDocument>().SetSortOrder(sortby).SetLimit(1);

Test:

private void Insert_Empleados(Empleados empleado)
{
    var coleccion = data.GetCollection<BsonDocument>("empleados");
    BsonDocument documento = empleado.ToBsonDocument();
    coleccion.InsertOne(documento);
    SortByBuilder sbb = new SortByBuilder();
    sbb.Descending("_id");
    var ultimo = coleccion.FindAllAs<BsonDocument>().SetSortOrder(sbb).SetLimit(1);
}

EDIT 2

coleccion.Find().SetSortOrder(SortBy.Descending("_id")).SetLimit(1);
    
answered by 13.12.2016 / 22:53
source
0

How could I solve my problem, thanks to @sioesi and @ Elenasys

My Class Employees

    public class Empleados
    {
        public string Nombre{ get; set; }
        public string Direccion { get; set; }
    }

Button Method

Empleados empleado= new Empleados ();
empleado.Nombre= "Rastalovely";
empleado.Direccion= "Mexico";
Insert_Empleados(empleado);

Private Method

private void Insert_Empleados(Empleados empleado)
    {
        var coleccion = data.GetCollection<BsonDocument>("empleados");
        BsonDocument documento = empleado.ToBsonDocument();
        coleccion.InsertOne(documento);

        var query = Query.Empty;
        var sortby = SortBy.Descending("_id");
        var afs0= coleccion.FindAs<BsonDocument>(query).SetSortOrder(sortby).SetLimit(1);

        var listado = afs0.ToList();
        foreach (var item in listado)
        {
            string elid = item["_id"].ToString();
        }
   }
    
answered by 14.12.2016 в 18:51