This post has already been read 8341 times!
Overview
Welcome to the Getting Started with MongoDB guide. This guide provides instructions to get you started using MongoDB. The guide covers the following topics:
- Introduction to MongoDB as well as instructions to Import Example Dataset;
- A brief overview of the C++ MongoDB Driver;
- Basic Insert, Find, Update, Remove operations plus Aggregation;
- Instructions on creating Indexes to improve query performance.
The MongoDB Shell Edition of this guide also includes instructions for installing MongoDB.
Introduction to MongoDB
MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling. MongoDB obviates the need for an Object Relational Mapping (ORM) to facilitate development.
Documents
A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.
{
"_id" : ObjectId("54c955492b7c8eb21818bd09"),
"address" : {
"street" : "2 Avenue",
"zipcode" : "10075",
"building" : "1480",
"coord" : [ -73.9557413, 40.7720266 ],
},
"borough" : "Manhattan",
"cuisine" : "Italian",
"grades" : [
{
"date" : ISODate("2014-10-01T00:00:00Z"),
"grade" : "A",
"score" : 11
},
{
"date" : ISODate("2014-01-16T00:00:00Z"),
"grade" : "B",
"score" : 17
}
],
"name" : "Vella",
"restaurant_id" : "41704620"
}
Collections
MongoDB stores documents in collections. Collections are analogous to tables in relational databases. Unlike a table, however, a collection does not require its documents to have the same schema.
In MongoDB, documents stored in a collection must have a unique _id field that acts as a primary key.
Import Example Dataset
Overview
The examples in this guide use the restaurants collection in the test database. The following is a sample document in the restaurants collection:
{
"address": {
"building": "1007",
"coord": [ -73.856077, 40.848447 ],
"street": "Morris Park Ave",
"zipcode": "10462"
},
"borough": "Bronx",
"cuisine": "Bakery",
"grades": [
{ "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
{ "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
{ "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
{ "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
{ "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
],
"name": "Morris Park Bake Shop",
"restaurant_id": "30075445"
}
Use the following procedure to populate the restaurants collection.
Prerequisites
You must have a running mongod instance in order to import data into the database.
Procedure
1. Retrieve the restaurants data.
Retrieve the dataset from https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/dataset.json and save to a file named primer-dataset.json.
2. Import data into the collection.
In the system shell or command prompt, use mongoimport to insert the documents into the restaurants collection in the test database. If the collection already exists in the test database, the operation will drop the restaurants collection first.
mongoimport --db test --collection restaurants --drop --file primer-dataset.json
The mongoimport connects to a mongod instance running on localhost on port number 27017.
To import data into a mongod instance running on a different host or port, specify the hostname or port by including the --host and the --port options in your mongoimport command.
C++ MongoDB Driver
MongoDB C++ Driver is the officially supported C++ driver for MongoDB.
Warning
The Getting Started guide uses a version of C++ driver that is currently in development. For documentation on the stable version of the C++ driver, see https://github.com/mongodb/mongo-cxx-driver/wiki#legacy-driver-documentation.
Procedure
1.Download the MongoDB C++ Driver
Download the source from https://github.com/mongodb/mongo-cxx-driver.
2.Compile the Driver
To compile, follow the build instructions on https://github.com/mongodb/mongo-cxx-driver/wiki/Quickstart-Guide-(New-Driver).
3.Connect to MongoDB
Use mongocxx::client class to connect to a running mongod instance.
Add the following code in your C++ program.
Add the following #include statements.
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
Include the following code in your program to create a client connection to a running mongod instance and use the test database.
mongocxx::instance inst{};
mongocxx::client conn{};
auto db = conn["test"];
Insert Data with C++ Driver
Overview
You can use the insert_one method to add documents to a collection in MongoDB. If you attempt to add documents to a collection that does not exist, MongoDB will create the collection for you.
Prerequisites
Add the following #include and using statements.
// Copyright 2015 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;
Include the following code in your program to create a client connection to a running mongod instance and use the test database.
mongocxx::instance inst{};
mongocxx::client conn{};
auto db = conn["test"];
Insert a Document
Insert a document into a collection named restaurants. The operation will create the collection if the collection does not currently exist.
bsoncxx::document::value restaurant_doc =
document{} << "address" << open_document << "street"
<< "2 Avenue"
<< "zipcode"
<< "10075"
<< "building"
<< "1480"
<< "coord" << open_array << -73.9557413 << 40.7720266 << close_array
<< close_document << "borough"
<< "Manhattan"
<< "cuisine"
<< "Italian"
<< "grades" << open_array << open_document << "date"
<< bsoncxx::types::b_date{12323} << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
<< bsoncxx::types::b_date{121212} << "grade"
<< "B"
<< "score" << 17 << close_document << close_array << "name"
<< "Vella"
<< "restaurant_id"
<< "41704620" << finalize;
// We choose to move in our document here, which transfers ownership to insert_one()
auto res = db["restaurants"].insert_one(std::move(restaurant_doc));
If the document passed to the insert_one method does not contain the _id field, the driver automatically adds the field to the document and sets the field’s value to a generated ObjectId.
Additional Information
In the C++ Driver documentation, see insert_one and bsoncxx::builder::stream::document.
In the MongoDB Manual, see also the Insert Documents tutorial.