Search code examples
mongodb.net-coremongodb-.net-driverobjectid

Contructor MongoDB.Bson.ObjectId() does not work in .NET Core 2


I have a first project who tries to get a value from mongodb using MongoDB.Driver. I can connect to the database and "GetAll" but when make a request who need ObjectId i receive that Exception:

Exception has occurred: CLR/System.IndexOutOfRangeException
An exception of type 'System.IndexOutOfRangeException' occurred in MongoDB.Bson.dll but was not handled in user code: 'Index was outside the bounds of the array.'

being more specific:

at MongoDB.Bson.ObjectId.FromByteArray(Byte[] bytes, Int32 offset, Int32& a, Int32& b, Int32& c)
   at MongoDB.Bson.ObjectId..ctor(String value)
   at TodoApi.Controllers.TodoController.GetById(String id) ...

Method GetById:

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
    var objId = new ObjectId(id); << this line exceptions occures
    var item = objds.GetTodoItem(objId);

    if (item == null) { return NotFound(); }

    return new ObjectResult(item);
}

Methodo GetTodoItem from DataAcess:

public TodoItem GetTodoItem(ObjectId id)
{
    var res = Query<TodoItem>.EQ(p=>p.Id,id);
    return _db.GetCollection<TodoItem>("TodoApi").FindOne(res);
}

.csproj

  <ItemGroup>
    <PackageReference Include="MongoDB.Driver" Version="2.5.0" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="MongoDB.Driver.Core" Version="2.5.0" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="MongoDB.Bson" Version="2.5.0" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="mongocsharpdriver" Version="2.5.0" />
  </ItemGroup>

Solution

  • You can generate a new ObjectId like this:

    ObjectId.GenerateNewId();
    

    But most likely you will not find any document in your database with that id. Usually, you generate an ObjectId when you want to do an Insert and do not want Mongo to assign a random id to your newly inserted document (let's say you want to return that id back to the user).

    Now, assuming you are looking for a specific document with id = 5a71ae10a41e1656a4a50902, you can do as follows:

    var id = "5a71ae10a41e1656a4a50902";
    var context = new YourContext();
    var builder = Builders<TodoItem>.Filter;
    var filter = builder.Eq(x => x.Id, ObjectId.Parse(id));
    var result = await context.TodoItemCollection.FindAsync(filter);