0

I am trying to return a single value from a collection in my MongoDB database, however I am getting a null value returned and a document with that id exists in the collection.

    public async Task<Business> GetBusiness(string businessId)
    {
        var objectId = new ObjectId(businessId);
        var filter = Builders<Business>.Filter.Eq("_id", objectId);
        var entity = await _businessMongoCollection.Find(filter).FirstAsync();
        return entity;
    }

I have also tried doing it this way but i get a null result.

var filter = Builders<Business>.Filter.Eq("_id", new ObjectId(businessId));
var foundBusinessTask = await _businessMongoCollection.FindAsync(filter);
var foundBusiness = await foundBusinessTask.SingleOrDefaultAsync();
floormind
  • 1,868
  • 5
  • 31
  • 85

1 Answers1

0

Could you not use the property specifier instead of the string "_id", like so:

var filter = Builders<Business>.Filter.Eq(b => b.Id, businessId);

I don't think you need to turn the id's into ObjectId

Sachin
  • 106
  • 1
  • 4
  • two issue with this, i'd have to ToString the b.Id like this var filter = Builders.Filter.Eq(b => b.Id.ToString(), businessId); and the second issue is that it still returns null – floormind Jun 05 '20 at 10:11
  • I am assuming that the Id property is of Guid type in your `Business` class. In which case you should not be passing that parameter `businessId` as string but Guid so the equality check in the filter as I have suggested will be comparing Guid to Guid. No `.ToString()` needed, although you might need `Guid.Parse(businessId)` – Sachin Jun 05 '20 at 16:27