Hary
Hary

Reputation: 5818

Mongo Collection Find By Id with Filter

To find one item from mongo collection, I am trying to apply filter and to the collection. But there is a compilation error as below.

enter image description here

This code is taken from official mongodb docs

var filter = Builders<BsonDocument>.Filter.Eq("_id", id);
var result = _collection.Find(filter);

Upvotes: 6

Views: 20783

Answers (2)

Amir Abrams
Amir Abrams

Reputation: 61

When the "_id" is a BsonType.ObjectId, you will need to use ObjectId.Parse like this:

var _collection = database.GetCollection<BsonDocument>("name");
var filter = Builders<BsonDocument>.Filter.Eq("_id", ObjectId.Parse(id));
var result = _collection.Find(filter);

Upvotes: 6

rnofenko
rnofenko

Reputation: 9533

Generic Type of Builder should be the same as for collection's generic type. In your case collection should have type BsonDocument.

var _collection = database.GetCollection<BsonDocument>("name");
var filter = Builders<BsonDocument>.Filter.Eq("_id", id);
var result = _collection.Find(filter);

Upvotes: 11

Related Questions