MongoDb delete

To delete a document in MongoDB using the C language, follow these steps:

  1. Include the necessary header files:
#include <stdio.h>
#include <bson.h>
#include <mongoc.h>
  1. Set up the MongoDB client and initialize it:
mongoc_client_t *client;
mongoc_database_t *database;
mongoc_collection_t *collection;

mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017");
database = mongoc_client_get_database (client, "mydb");
collection = mongoc_client_get_collection (client, "mydb", "mycollection");
  1. Create a query to specify the document to be deleted:
bson_t *query;
query = bson_new ();
BSON_APPEND_UTF8 (query, "name", "John Doe");
  1. Execute the delete operation:
mongoc_delete_result_t *result;
result = mongoc_collection_delete_many (collection, query, NULL, NULL);
  1. Check the result and handle any errors:
if (!result) {
    // Handle error
} else {
    // Process the result
}

mongoc_delete_result_destroy (result);
bson_destroy (query);
  1. Clean up and release resources:
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_client_destroy (client);
mongoc_cleanup ();

These steps demonstrate how to delete a document from a MongoDB collection using the C language and the official MongoDB C Driver.