Overview
In this guide, you can learn how to use the C driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. MongoDB Search indexes specify the behavior of the search and which fields to index.
Sample Data
The example in this guide uses the movies collection in the sample_mflix
database from the Atlas sample datasets. To learn how to
create a free MongoDB Atlas cluster and load the sample datasets, see the
Get Started guide.
Run a MongoDB Search Query
This section shows how to create an aggregation pipeline to run a
MongoDB Search query on a collection. In your bson_t structure that represents
your pipeline stages, add the $search stage to specify the search criteria.
Then, call the mongoc_collection_aggregate() function and pass your pipeline
as a parameter.
Tip
To learn more about aggregation operations, see the Aggregation guide.
Before running a MongoDB Search query, you must create a MongoDB Search index on your collection. To learn how to programmatically create a MongoDB Search index, see the Create a Search Index section of the MongoDB Search Indexes guide.
MongoDB Search Example
This example runs a MongoDB Search query by performing the following actions:
Creates a
$searchstage that instructs the driver to query for documents in which thetitlefield contains the word"Alabama"Creates a
$projectstage that instructs the driver to include thetitlefield in the query resultsPasses the pipeline stages to the
mongoc_collection_aggregate()function and prints the results
const bson_t *doc; bson_t *pipeline = BCON_NEW("pipeline", "[", "{", "$search", "{", "index", BCON_UTF8("<index name>"), "text", "{", "query", BCON_UTF8("Alabama"), "path", BCON_UTF8("title"), "}", "}", "}", "{", "$project", "{", "title", BCON_INT32(1), "}", "}", "]"); mongoc_cursor_t *results = mongoc_collection_aggregate(collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); while (mongoc_cursor_next(results, &doc)) { char *str = bson_as_canonical_extended_json(doc, NULL); printf("%s\n", str); bson_free(str); } bson_destroy(pipeline); mongoc_cursor_destroy(results);
{ "_id" : { "$oid" : "..." }, "title" : "Alabama Moon" } { "_id" : { "$oid" : "..." }, "title" : "Sweet Home Alabama" } { "_id" : { "$oid" : "..." }, "title" : "Crazy in Alabama" }
Additional Information
To learn more about MongoDB Search, see MongoDB Search in the Atlas documentation.
API Documentation
To learn more about the mongoc_collection_aggregate() function, see the
API documentation.