2

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.

3
  • Which driver are you using to connect to Mongo? Also, how does the data look within Mongo? Commented Oct 2, 2015 at 7:29
  • @Dr Schizo I use the official driver. The manufacture is a string field of the car entity. Commented Oct 2, 2015 at 7:37
  • can we get an example of what it looks like in Mongo? As what you are requesting we really need to know what the data looks like. Commented Oct 2, 2015 at 7:52

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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');.

3 Comments

I can't find this method in the latest version of MongoDB driver for C#, but DistinctAnsync, which takes different parameters.
This should be a comment
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.