Skip to content

Commit bd69fc6

Browse files
authored
DOCSP-28393 C# new atlas search examples (#521)
1 parent bd02e59 commit bd69fc6

File tree

2 files changed

+139
-7
lines changed

2 files changed

+139
-7
lines changed

source/fundamentals/atlas-search.txt

Lines changed: 92 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,11 @@ categorizes data in a searchable format.
7373
To learn how to create an Atlas Search Index see the
7474
:atlas:`Create an Atlas Search Index </atlas-search/create-index>` Atlas guide.
7575

76-
Atlas Search Operators
77-
----------------------
76+
Atlas Search Operators and Collectors
77+
-------------------------------------
7878

7979
The ``Search`` class contains methods you can use to perform ``$search``
80-
operations. For a full list of available ``$search`` operators, see the :atlas:`Operators and Collectors
80+
operations. For a full list of available ``$search`` operators and collectors, see the :atlas:`Operators and Collectors
8181
</atlas-search/operators-and-collectors>` Atlas guide.
8282

8383
Autocomplete
@@ -243,6 +243,40 @@ The search returns the following documents:
243243
To learn more about the ``exists`` operator, see the :atlas:`exists </atlas-search/exists>`
244244
Atlas guide.
245245

246+
Facet
247+
~~~~~
248+
249+
Use the ``Facet()`` method to group results by values or ranges in the specified faceted fields
250+
and return the count for each of those groups.
251+
252+
You can use the ``Facet()`` method with both the ``$search`` and ``$searchMeta`` stages. MongoDB recommends using
253+
facet with the ``$searchMeta`` stage to retrieve metadata results only for the query.
254+
To retrieve metadata results and query results using the ``$search`` stage, you must use the
255+
``$$SEARCH_META`` aggregation variable. To learn more about this variable, see the :atlas:`SEARCH_META Aggregation Variable </atlas-search/facet/#std-label-fts-facet-aggregation-variable>` Atlas guide.
256+
257+
The following limitations apply:
258+
259+
- You can run facet queries on a single field only. You can't run facet queries on groups of fields.
260+
- You can run facet queries over sharded collections on clusters running MongoDB v6.0 only.
261+
262+
The following example searches the ``guitars`` collection for any documents in
263+
which the value of the ``in_stock`` field is ``true``. The query uses the ``Facet()`` method to process the input documents, with a maximum number of ``100`` facet categories to return in the results. The query returns the total count of documents in which the value of ``in_stock`` is ``true``.
264+
265+
.. literalinclude:: /includes/fundamentals/code-examples/atlas-search/AtlasSearchExamples.cs
266+
:start-after: // start-facet-search
267+
:end-before: // end-facet-search
268+
:language: csharp
269+
:dedent:
270+
271+
The search returns the following result:
272+
273+
.. code-block:: none
274+
275+
4
276+
277+
To learn more about the ``facet`` collector, see the :atlas:`facet </atlas-search/facet>`
278+
Atlas guide.
279+
246280
GeoShape
247281
~~~~~~~~
248282

@@ -703,6 +737,60 @@ The search returns the following document:
703737
To learn more about the ``wildcard`` operator, see the :atlas:`wildcard </atlas-search/wildcard>`
704738
Atlas guide.
705739

740+
Search Multiple Fields
741+
----------------------
742+
743+
The ``path`` parameter is used by the Atlas Search
744+
:atlas:`operators </atlas-search/query-syntax>` to specify the field or fields
745+
to be searched. To learn more about what the ``path`` parameter may contain, see the :atlas:`Construct a Query Path </atlas-search/path-construction>` guide.
746+
747+
.. note::
748+
749+
Not all operators can use all the different types of paths. See the
750+
documentation for each individual operator for details on what types
751+
of path it supports.
752+
753+
To search multiple indexed fields, use the ``Multi()`` method and pass in your fields. Documents which match on any of the specified fields are included in the result set.
754+
755+
The following example searches for the string ``classic`` in either the ``make`` or the ``description`` field.
756+
757+
.. literalinclude:: /includes/fundamentals/code-examples/atlas-search/AtlasSearchExamples.cs
758+
:start-after: // start-multiple-field-search
759+
:end-before: // end-multiple-field-search
760+
:language: csharp
761+
:dedent:
762+
763+
The search returns the following documents:
764+
765+
.. code-block:: json
766+
767+
{ "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "rating" : 9}
768+
{ "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 1902, "in_stock" : true, "rating" : 8}
769+
770+
Score Documents
771+
---------------
772+
773+
Every document returned by an Atlas Search query is assigned a score based on relevance, and the documents included in a result set are returned in order from highest score to lowest. To learn more about how scores are assigned, see the :atlas:`score </atlas-search/scoring>` Atlas guide.
774+
775+
The score assigned to a returned document is part of the document's metadata. You can include each returned document's score along with the result set by using a ``$project`` stage in your aggregation pipeline.
776+
777+
The following example searches the ``guitars`` collection for documents in which the value of the ``make`` field contains exactly six letters and uses a ``$project`` stage to add a field named ``score`` to the returned documents.
778+
779+
.. literalinclude:: /includes/fundamentals/code-examples/atlas-search/AtlasSearchExamples.cs
780+
:start-after: // start-score-search
781+
:end-before: // end-score-search
782+
:language: csharp
783+
:dedent:
784+
785+
The search returns the following documents:
786+
787+
.. code-block:: json
788+
789+
{ "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 0, "in_stock" : false, "rating" : null, "score" : 1.0 }
790+
{ "_id" : 4, "make" : "Kiesel", "description" : "Quality guitars made only for custom orders.", "establishedYear" : 0, "in_stock" : false, "rating" : null, "score" : 1.0 }
791+
{ "_id" : 5, "make" : "Ibanez", "description" : "Well-crafted guitars used by many professional guitarists.", "establishedYear" : 0, "in_stock" : false, "rating" : null, "score" : 1.0 }
792+
{ "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 0, "in_stock" : false, "rating" : null, "score" : 1.0 }
793+
706794
Modify Atlas Search Behavior
707795
----------------------------
708796

@@ -814,4 +902,4 @@ The search returns the following document:
814902
.. tip::
815903

816904
To learn more about Atlas Search pagination, see :atlas:`Paginate the Results </atlas-search/paginate-results/>`
817-
in the Atlas documentation.
905+
in the Atlas documentation.

source/includes/fundamentals/code-examples/atlas-search/AtlasSearchExamples.cs

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,22 @@ public static List<Guitar> ExistsSearch()
8787
return result;
8888
}
8989

90+
public static int FacetSearch()
91+
{
92+
// start-facet-search
93+
var result = guitarsCollection.Aggregate()
94+
.SearchMeta(
95+
Builders<Guitar>.Search.Facet(
96+
Builders<Guitar>.Search.Equals(g => g.InStock, true),
97+
Builders<Guitar>.SearchFacet.String("string", g => g.Make, 100)),
98+
indexName: "guitarfacetsearch")
99+
.Single()
100+
.Facet["string"].Buckets.Count();
101+
// end-facet-search
102+
103+
return result;
104+
}
105+
90106
public static List<Guitar> GeoShapeSearch()
91107
{
92108
// start-geoshape-search
@@ -274,6 +290,33 @@ public static List<Guitar> WildcardSearch()
274290
return result;
275291
}
276292

293+
public static List<Guitar> MultipleFieldSearch()
294+
{
295+
// start-multiple-field-search
296+
var result = guitarsCollection.Aggregate().Search(
297+
Builders<Guitar>.Search.Phrase(Builders<Guitar>.SearchPath
298+
.Multi(g => g.Description, g => g.Make), "classic"), indexName: "guitarmulti")
299+
.ToList();
300+
// end-multiple-field-search
301+
302+
return result;
303+
}
304+
305+
public static List<Guitar> ScoreSearch()
306+
{
307+
// start-score-search
308+
var regex = "[A-Za-z]{6}";
309+
310+
var result = guitarsCollection.Aggregate()
311+
.Search(Builders<Guitar>.Search.Regex(g => g.Make, regex, allowAnalyzedField: true), indexName: "guitarscore")
312+
.Project<Guitar>(Builders<Guitar>.Projection
313+
.Include("Id")
314+
.Include("Make")
315+
.Include("Description")
316+
.MetaSearchScore(g => g.Score))
317+
.ToList();
318+
// end-score-search
319+
277320
public static List<Guitar> SearchAfter()
278321
{
279322
// start-pagination-options
@@ -309,10 +352,10 @@ private static void Setup()
309352
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
310353
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
311354

312-
// Establish the connection to MongoDB and get the restaurants database
355+
// Establish the connection to MongoDB and get the guitars database
313356
var mongoClient = new MongoClient(_mongoConnectionString);
314-
var restaurantsDatabase = mongoClient.GetDatabase("sample_guitars");
315-
guitarsCollection = restaurantsDatabase.GetCollection<Guitar>("guitars");
357+
var guitarsDatabase = mongoClient.GetDatabase("sample_guitars");
358+
guitarsCollection = guitarsDatabase.GetCollection<Guitar>("guitars");
316359
}
317360
}
318361

@@ -333,6 +376,7 @@ public class Guitar
333376
[BsonElement("in_stock_location")]
334377
public Location InStockLocation { get; set; }
335378
public int? Rating { get; set; }
379+
public double Score {get; set;}
336380
[BsonElement("paginationToken")]
337381
public string PaginationToken { get; set; }
338382
}

0 commit comments

Comments
 (0)