1+ using MongoDB . Bson . Serialization . Conventions ;
2+ using MongoDB . Driver ;
3+
4+ namespace CSharpExamples . UsageExamples . FindMany ;
5+
6+ public class FindMany
7+ {
8+ private static IMongoCollection < Restaurant > _restaurantsCollection ;
9+ private const string MongoConnectionString = "<Your MongoDB URI>" ;
10+
11+ public static void Main ( string [ ] args )
12+ {
13+ Setup ( ) ;
14+
15+ // Find multiple documents using builders
16+ Console . WriteLine ( "Finding documents with builders...:" ) ;
17+ var restaurants = FindMultipleRestaurantsBuilderSync ( ) ;
18+ Console . WriteLine ( $ "Number of documents found: { restaurants . Count } ") ;
19+
20+ // Extra space for console readability
21+ Console . WriteLine ( ) ;
22+
23+ // Find multiple documents using LINQ
24+ Console . WriteLine ( "Finding documents with LINQ...:" ) ;
25+ restaurants = FindMultipleRestaurantsLinqSync ( ) ;
26+ Console . WriteLine ( $ "Number of documents found: { restaurants . Count } ") ;
27+
28+ Console . WriteLine ( ) ;
29+
30+ // Find all restaurants
31+ Console . WriteLine ( "Finding all documents...:" ) ;
32+ restaurants = FindAllRestaurantsSync ( ) ;
33+ Console . WriteLine ( $ "Number of documents found: { restaurants . Count } ") ;
34+ }
35+
36+ public static List < Restaurant > FindMultipleRestaurantsBuilderSync ( )
37+ {
38+ // start-find-builders-sync
39+ var filter = Builders < Restaurant > . Filter
40+ . Eq ( "cuisine" , "Pizza" ) ;
41+
42+ return _restaurantsCollection . Find ( filter ) . ToList ( ) ;
43+ // end-find-builders-sync
44+ }
45+
46+ public static List < Restaurant > FindMultipleRestaurantsLinqSync ( )
47+ {
48+ // start-find-linq-sync
49+ return _restaurantsCollection . AsQueryable ( )
50+ . Where ( r => r . Cuisine == "Pizza" ) . ToList ( ) ;
51+ // end-find-linq-sync
52+ }
53+
54+ private static List < Restaurant > FindAllRestaurantsSync ( )
55+ {
56+ // start-find-all-sync
57+ var filter = Builders < Restaurant > . Filter . Empty ;
58+
59+ return _restaurantsCollection . Find ( filter )
60+ . ToList ( ) ;
61+ // end-find-all-sync
62+ }
63+
64+ private static void Setup ( )
65+ {
66+ // This allows automapping of the camelCase database fields to our models.
67+ var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention ( ) } ;
68+ ConventionRegistry . Register ( "CamelCase" , camelCaseConvention , type => true ) ;
69+
70+ // Establish the connection to MongoDB and get the restaurants database
71+ var mongoClient = new MongoClient ( MongoConnectionString ) ;
72+ var restaurantsDatabase = mongoClient . GetDatabase ( "sample_restaurants" ) ;
73+ _restaurantsCollection = restaurantsDatabase . GetCollection < Restaurant > ( "restaurants" ) ;
74+ }
75+ }
0 commit comments