MongoDB basic operation and C interface using-MONGODB C Driver

Source: Internet
Author: User
Tags mongodb


Official website http://mongoc.org/libmongoc/current/tutorial.html

Download wget https://github.com/mongodb/mongo-c-driver/releases/download/1.6.3/mongo-c-driver-1.6.3.tar.gz
$ tar xzf mongo-c-driver-1.6.3.tar.gz
$ CD mongo-c-driver-1.6.3
$./configure--disable-automatic-init-and-cleanup
starting mongodb¶

To run the examples in this tutorial, MongoDB must is installed and running on localhost on the default port, 27017. To check if it's up and running, connect to it with the MongoDB shell.

$ MONGO--host localhost--port 27017 MongoDB
shell version:3.0.6 connecting to:localhost:27017/test
>
Making a connection¶

The C Driver provides a convenient way to access MongoDB--regardless of cluster configuration--via a mongoc_client_t. It transparently connects to standalone servers, replica sets and sharded on clusters. Once a connection has been made, handles to databases and collections can is obtained via the structs mongoc_database_t an D mongoc_collection_t, respectively. MongoDB operations can then is performed through these handles.

At the "start of" a application, call Mongoc_init () before the "other" LIBMONGOC functions and call Mongoc_cleanup () before E Xiting. When creating handles to clients, databases and servers, call the appropriate destroy when functions.

The example below establishes a connection to a standalone server on localhost, registers the client application as "Co Nnect-example, "and performs a simple command. More information about database operations can is found in the CRUD operations and executing Commands. Examples of connecting to replica sets and sharded clusters can is found on the Advanced Connections page.

#include <bson.h> #include <bcon.h> #include <mongoc.h> int main (int argc, char *argv[]) {
   mongoc_client_t *client;
   mongoc_database_t *database;
   Mongoc_collection_t *collection;
   Bson_t *command, reply, *insert;
   bson_error_t error;
   Char *str;

   BOOL retval;

   * * Required to initialize LIBMONGOC ' s internals * * MONGOC_INIT ();

   * * Create A new Client instance * * client = mongoc_client_new ("mongodb://localhost:27017"); /* Register The application name so we can-track it in the profiles logs * on the server.
    This can also is done from the URI ("other examples").

   * * Mongoc_client_set_appname (client, "Connect-example");  * * Get a handle on the database "Db_name" and Collection "Coll_name"/database = Mongoc_client_get_database
   (Client, "db_name"); Collection = Mongoc_client_get_collection (client, "Db_name", "coll_name"); * * do work. This is example pings the database, prints the result as JSON and * performs a insert/Command = bcon_new ("Pin

   G ", Bcon_int32 (1));

   retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error);
      if (!retval) {fprintf (stderr, "%s\n", error.message);
   return exit_failure;
   str = Bson_as_json (&reply, NULL);

   printf ("%s\n", str);

   Insert = bcon_new ("Hello", Bcon_utf8 ("World"));  if (!mongoc_collection_insert (collection, Mongoc_insert_none, insert, NULL, &error)) {fprintf (stderr, "%s\n"),
   Error.message);
   } bson_destroy (insert);
   Bson_destroy (&reply);
   Bson_destroy (command);

   Bson_free (str);
   * * Release we handles and clean up LIBMONGOC * * Mongoc_collection_destroy (collection);
   Mongoc_database_destroy (database);
   Mongoc_client_destroy (client); Mongoc_cleanup ();
return 0;
 }

On a unix-like system, the code can is compiled and run like so:

$ gcc-o Connect connect.c $ (pkg-config--cflags--libs libmongoc-1.0)
$./connect
{"OK": 1.000000}

Alternatively, if Pkg-config is isn't available, paths and libraries can be managed manually.

$ gcc-o Connect connect.c-i/usr/local/include-lmongoc-1.0-lbson-1.0
$/connect
{"OK": 1.000000}

For Windows users, the code can is compiled and run with the following commands. (This assumes is the MongoDB C Driver has been installed to C:\mongo-c-driver; Change the include directory as needed.)

c:\> cl.exe/ic:\mongo-c-driver\include\libbson-1.0/ic:\mongo-c-driver\include\libmongoc-1.0 connect.c
C:\ > Connect
{"OK": 1.000000}
Creating Bson documents¶

Documents are stored in MongoDB ' s data format, Bson. The C driver uses Libbson to create Bson documents. There are several ways to construct them:appending Key-value, using pairs, or Bcon JSON. appending bson¶

A Bson document, represented as a bson_t in code, can is constructed one field at a time using Libbson ' s append functions.

For example, to create a document like this:

{
   born:isodate ("1906-12-09"),
   died:isodate ("1992-01-01"),
   name: {
      A: "Grace", Last
      : "  Hopper "
   },
   languages: [" Math-matic "," flow-matic "," COBOL "],
   degrees: [{degree:" BA ", School:" Vassar "}, {degree: "PhD", School: "Yale"}]
}

Use the following code:

#include <bson.h> int main (int argc, char *argv[]) {struct TM born = {0};
   struct TM died = {0};
   const char *lang_names[] = {"Math-matic", "flow-matic", "COBOL"};
   const char *schools[] = {"Vassar", "Yale"};
   const char *degrees[] = {"BA", "PhD"};
   uint32_t i;
   Char buf[16];
   const char *key;
   size_t Keylen;
   Bson_t *document;
   bson_t child;
   Bson_t child2;

   Char *str;

   Document = Bson_new ();
    * * Append {"Born": Isodate ("1906-12-09")} to the document.
    * Passing-1 for the length argument tells Libbson to calculate the string length.  * * Born.tm_year = 6;  /* years are 1900-based * * Born.tm_mon = 11;
   /* months are 0-based * * Born.tm_mday = 9;

   Bson_append_date_time (document, "Born",-1, Mktime (&born) * 1000);
    * * Append {"died": Isodate ("1992-01-01")} to the document.
   * * Died.tm_year = 92;
   Died.tm_mon = 0;

   Died.tm_mday = 1; /* For convenience, this is macro passes length-1 by default.

   * * Bson_append_date_time (document, "died", Mktime (&died) * 1000);
    * * Append a subdocument.
   * * Bson_append_document_begin (DOCUMENT, "name", &child);
   Bson_append_utf8 (&child, "a", "Grace");
   Bson_append_utf8 (&child, "Last", "Hopper");

   Bson_append_document_end (document, &child); * * Append array of strings.
    Generate Keys "0", "1", "2".
   * * Bson_append_array_begin (document, "languages", &child); for (i = 0; i < sizeof lang_names/sizeof (char *); ++i) {Keylen = Bson_uint32_to_string (i, &key, buf, siz
      EOF BUF);
   Bson_append_utf8 (&child, key, (int) Keylen, lang_names[i],-1);

   Bson_append_array_end (document, &child);
    * * Array of subdocuments: * degrees: [{degree: "BA", School: "Vassar"}, ...]
   * * Bson_append_array_begin (document, "degrees", &child); for (i = 0; i < SizeoF degrees/sizeof (char *);
      ++i) {Keylen = Bson_uint32_to_string (i, &key, buf, sizeof buf);
      Bson_append_document_begin (&child, key, (int) Keylen, &child2);
      Bson_append_utf8 (&child2, "degree", degrees[i]);
      Bson_append_utf8 (&child2, "school", Schools[i]);
   Bson_append_document_end (&child, &child2);

   Bson_append_array_end (document, &child);
    /* Print the document as a JSON string.
   */str = Bson_as_json (document, NULL);
   printf ("%s\n", str);

   Bson_free (str);
    * * Clean up allocated Bson documents.
   * * Bson_destroy (document);
return 0;
 }

The Libbson documentation for all of the types that can is appended to a bson_t. Using bcon¶

Bson C Object notation, Bcon for short, are an alternative way of constructing bson documents in a manner to the int Ended format. It has less type-safety than Bson ' s append functions, but results in less code.

 #include <bson.h> int main (int argc, char *argv[]) {struct TM born = {0};
   struct TM died = {0};
   Bson_t *document;

   Char *str;
   Born.tm_year = 6;
   Born.tm_mon = 11;

   Born.tm_mday = 9;
   Died.tm_year = 92;
   Died.tm_mon = 0;

   Died.tm_mday = 1; Document = Bcon_new ("Born", Bcon_date_time (Mktime (&born) * 1000), "died", Bcon_date_time (mktime
      ;d IED) * 1000), "name", "{", "a", "Bcon_utf8" ("Grace"), "Last", Bcon_utf8 ("Hopper"), "}",
      "Languages", "[", Bcon_utf8 ("math-matic"), Bcon_utf8 ("flow-matic"), Bcon_utf8 ("COBOL"), "]", 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.