Sasha White
Sasha White

Reputation: 13

How to retrive only specific fields form MongoDB using C#

For instance I have a database of cars, which have a field called manufacture.

car: {
     _id: <ObjectId>,
     manufacture: "Opel",
     model: "Astra"
}

How can I get all manufactures without repeating them using the latest implementation official C# driver for MongoDB?

I'd like this to be done in my request to the database, not after.

Upvotes: 1

Views: 7128

Answers (2)

Shanoor
Shanoor

Reputation: 13672

Use the Distinct() method: http://api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoCollection_Distinct.htm

The field name should be passed as a string, some generic MongoDB examples: http://docs.mongodb.org/manual/reference/method/db.collection.distinct/

Following some examples, it should look like this: var result = await collection.Distinct('manufacture');.

Upvotes: 0

XtremeBytes
XtremeBytes

Reputation: 1497

This should do it

        var db = database.GetCollection<BsonDocument>("cars");

        FieldDefinition<BsonDocument, string> field = "car.manufacture";
        FilterDefinition<BsonDocument> filter = new BsonDocument();

        var a = db.DistinctAsync(field, filter).GetAwaiter().GetResult().ToListAsync().GetAwaiter().GetResult();

Upvotes: 4

Related Questions