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>

2 Answers2

0

The problem is the line about create new objectID. mongoDB supplies default document IDs automatically, and you just first, find the ID then query the collection using that.

Off course you can change the default behaviour - see

http://codingcanvas.com/using-mongodb-_id-field-with-c-pocos/

Change this line:

var objId = new ObjectId(id); 

To something like this (you have to change the objectid.Parse() argument to your values.

var query_id = Query.EQ("_id",    
ObjectId.Parse("50ed4e7d5baffd13a44d0153"));
var entity = dbCollection.FindOne(query_id);
return entity.ToString();

Also, this line has typo, did you meant objId after the = sign?

 var item = objds.GetTodoItem(objId)

Credits: Query MongoDB Using 'ObjectId'

salah-1
  • 1,299
  • 11
  • 15
  • i tried the solution but not works in my case can you help me on below query https://stackoverflow.com/questions/74835380/how-to-do-a-partial-search-of-mongdb-object-id-in-c-sharp – Mohamed Sahir Dec 17 '22 at 15:49
0

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);
Mahdi
  • 3,199
  • 2
  • 25
  • 35
  • I understand now. I changed my method to look for the ID not by ObjectID `public TodoItem GetTodoItem(int id) { var res = Query.EQ(t => t.TodoId, id); return _db.GetCollection("TodoApi").FindOne(res); }` – Fernando Veras Apr 16 '18 at 16:28