Mongodb For Mac
- Mongodb For Local Machine
- Mongodb For Machine Learning
- Mongodb Tutorial For Mac
- Install Mongodb For Mac Os
- Mongodb Shell For Mac
Robo 3T (formerly Robomongo) is the free, lightweight, open-source MongoDB GUI with an embedded mongo shell, real auto-completion, and support for MongoDB 4.0. I have Docker installed and am running a MongoDB container for my local development on my Mac. The problem is that I can't connect to said DB easily from CLI. I have Robo 3T installed, but I would prefer to use the CLI client instead. Is there a known way to install JUST the mongo shell (command mongo) and not the full DB distribution on OS X?
MongoDB is an open source, cross platform document-oriented database management system. It is a NoSQL database which stores data and schemas as JSON objects. Mongodb is developed by Mongodb Inc and is published under GNU affero General Public License and Apache.
This tutorial describes the steps involved in the installation of MongoDB on MacOS
Prerequisites
- MacOS
- Login as an administrator on terminal.
- Homebrew must be installed on the system.
Installation
Following steps are used to install MongoDB on MacOS.
1) Update homebrew installer package
To get started with the installation of MongoDB on MacOS, we need to update the repository index of Homebrew package Installer. This will be done with the following command.
2) Install MongoDB
After updating the repository index, we need to install MongoDB which will be done with the help of homebrew installer. It simply installs the MongoDB on location /usr/local/Cellar/mongodb
3) Start MongoDB
To start MongoDB, we need to run the following command.
4) Working on command line
The MongoDB shell can be accessed by running the file named as mongo which is a executable script located inside the bin folder under installation directory.
To create database, we use following command on the MongoDB shell.
5) Stop database
To stop database, we have to specify unload option with the launchctl command as follows:
Well, we have installed MongoDB version 3.4.9 successfully on our MacOS.
-->
By Pratik Khandelwal and Scott Addie
This tutorial creates a web API that performs Create, Read, Update, and Delete (CRUD) operations on a MongoDB NoSQL database.
In this tutorial, you learn how to:
- Configure MongoDB
- Create a MongoDB database
- Define a MongoDB collection and schema
- Perform MongoDB CRUD operations from a web API
- Customize JSON serialization
View or download sample code (how to download)
Prerequisites
- Visual Studio 2019 with the ASP.NET and web development workload
Configure MongoDB
If using Windows, MongoDB is installed at C:Program FilesMongoDB by default. Add C:Program FilesMongoDBServer<version_number>bin to the Path
environment variable. This change enables MongoDB access from anywhere on your development machine.
Use the mongo Shell in the following steps to create a database, make collections, and store documents. For more information on mongo Shell commands, see Working with the mongo Shell.
Choose a directory on your development machine for storing the data. For example, C:BooksData on Windows. Create the directory if it doesn't exist. The mongo Shell doesn't create new directories.
Open a command shell. Run the following command to connect to MongoDB on default port 27017. Remember to replace
<data_directory_path>
with the directory you chose in the previous step.Open another command shell instance. Connect to the default test database by running the following command:
Run the following in a command shell:
If it doesn't already exist, a database named BookstoreDb is created. If the database does exist, its connection is opened for transactions.
Create a
Books
collection using following command:The following result is displayed:
Define a schema for the
Books
collection and insert two documents using the following command:The following result is displayed:
Note
The ID's shown in this article will not match the IDs when you run this sample.
View the documents in the database using the following command:
The following result is displayed:
The schema adds an autogenerated
_id
property of typeObjectId
for each document.
The database is ready. You can start creating the ASP.NET Core web API.
Create the ASP.NET Core web API project
Go to File > New > Project.
Select the ASP.NET Core Web Application project type, and select Next.
Name the project BooksApi, and select Create.
Select the .NET Core target framework and ASP.NET Core 3.0. Select the API project template, and select Create.
Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. In the Package Manager Console window, navigate to the project root. Run the following command to install the .NET driver for MongoDB:
Run the following commands in a command shell:
A new ASP.NET Core web API project targeting .NET Core is generated and opened in Visual Studio Code.
After the status bar's OmniSharp flame icon turns green, a dialog asks Required assets to build and debug are missing from 'BooksApi'. Add them?. Select Yes.
Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. Open Integrated Terminal and navigate to the project root. Run the following command to install the .NET driver for MongoDB:
- Go to File > New Solution > .NET Core > App.
- Select the ASP.NET Core Web API C# project template, and select Next.
- Select .NET Core 3.0 from the Target Framework drop-down list, and select Next.
- Enter BooksApi for the Project Name, and select Create.
- In the Solution pad, right-click the project's Dependencies node and select Add Packages.
- Enter MongoDB.Driver in the search box, select the MongoDB.Driver package, and select Add Package.
- Select the Accept button in the License Acceptance dialog.
Add an entity model
Add a Models directory to the project root.
Add a
Book
class to the Models directory with the following code:In the preceding class, the
Id
property:- Is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
- Is annotated with [BsonId] to designate this property as the document's primary key.
- Is annotated with [BsonRepresentation(BsonType.ObjectId)] to allow passing the parameter as type
string
instead of an ObjectId structure. Mongo handles the conversion fromstring
toObjectId
.
The
BookName
property is annotated with the [BsonElement] attribute. The attribute's value ofName
represents the property name in the MongoDB collection.
Add a configuration model
Flight sim x for mac pro. Add the following database configuration values to appsettings.json:
Add a BookstoreDatabaseSettings.cs file to the Models directory with the following code:
The preceding
BookstoreDatabaseSettings
class is used to store the appsettings.json file'sBookstoreDatabaseSettings
property values. The JSON and C# property names are named identically to ease the mapping process.Add the following highlighted code to
Startup.ConfigureServices
:In the preceding code:
- The configuration instance to which the appsettings.json file's
BookstoreDatabaseSettings
section binds is registered in the Dependency Injection (DI) container. For example, aBookstoreDatabaseSettings
object'sConnectionString
property is populated with theBookstoreDatabaseSettings:ConnectionString
property in appsettings.json. - The
IBookstoreDatabaseSettings
interface is registered in DI with a singleton service lifetime. When injected, the interface instance resolves to aBookstoreDatabaseSettings
object.
- The configuration instance to which the appsettings.json file's
Add the following code to the top of Startup.cs to resolve the
BookstoreDatabaseSettings
andIBookstoreDatabaseSettings
references:
Add a CRUD operations service
Add a Services directory to the project root.
Add a
BookService
class to the Services directory with the following code:In the preceding code, an
IBookstoreDatabaseSettings
instance is retrieved from DI via constructor injection. This technique provides access to the appsettings.json configuration values that were added in the Add a configuration model section.Add the following highlighted code to
Startup.ConfigureServices
:In the preceding code, the
BookService
class is registered with DI to support constructor injection in consuming classes. The singleton service lifetime is most appropriate becauseBookService
takes a direct dependency onMongoClient
. Per the official Mongo Client reuse guidelines,MongoClient
should be registered in DI with a singleton service lifetime.Add the following code to the top of Startup.cs to resolve the
BookService
reference:
The BookService
class uses the following MongoDB.Driver
members to perform CRUD operations against the database:
MongoClient – Reads the server instance for performing database operations. The constructor of this class is provided the MongoDB connection string:
IMongoDatabase – Represents the Mongo database for performing operations. This tutorial uses the generic GetCollection<TDocument>(collection) method on the interface to gain access to data in a specific collection. Perform CRUD operations against the collection after this method is called. In the
GetCollection<TDocument>(collection)
method call:collection
represents the collection name.TDocument
represents the CLR object type stored in the collection.
GetCollection<TDocument>(collection)
returns a MongoCollection object representing the collection. In this tutorial, the following methods are invoked on the collection:
- DeleteOne – Deletes a single document matching the provided search criteria.
- Find<TDocument> – Returns all documents in the collection matching the provided search criteria.
- InsertOne – Inserts the provided object as a new document in the collection.
- ReplaceOne – Replaces the single document matching the provided search criteria with the provided object.
Add a controller
Add a BooksController
class to the Controllers directory with the following code:
The preceding web API controller:
- Uses the
BookService
class to perform CRUD operations. - Contains action methods to support GET, POST, PUT, and DELETE HTTP requests.
- Calls CreatedAtRoute in the
Create
action method to return an HTTP 201 response. Status code 201 is the standard response for an HTTP POST method that creates a new resource on the server.CreatedAtRoute
also adds aLocation
header to the response. TheLocation
header specifies the URI of the newly created book.
Test the web API
Build and run the app.
Navigate to
http://localhost:<port>/api/books
to test the controller's parameterlessGet
action method. The following JSON response is displayed:Navigate to
http://localhost:<port>/api/books/{id here}
to test the controller's overloadedGet
action method. The following JSON response is displayed:
Configure JSON serialization options
There are two details to change about the JSON responses returned in the Test the web API section:
- The property names' default camel casing should be changed to match the Pascal casing of the CLR object's property names.
- The
bookName
property should be returned asName
.
To satisfy the preceding requirements, make the following changes:
JSON.NET has been removed from ASP.NET shared framework. Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson.
In
Startup.ConfigureServices
, chain the following highlighted code on to theAddMvc
method call:With the preceding change, property names in the web API's serialized JSON response match their corresponding property names in the CLR object type. For example, the
Book
class'sAuthor
property serializes asAuthor
.In Models/Book.cs, annotate the
BookName
property with the following [JsonProperty] attribute:The
[JsonProperty]
attribute's value ofName
represents the property name in the web API's serialized JSON response.Add the following code to the top of Models/Book.cs to resolve the
[JsonProperty]
attribute reference:Repeat the steps defined in the Test the web API section. Notice the difference in JSON property names.
This tutorial creates a web API that performs Create, Read, Update, and Delete (CRUD) operations on a MongoDB NoSQL database.
In this tutorial, you learn how to:
- Configure MongoDB
- Create a MongoDB database
- Define a MongoDB collection and schema
- Perform MongoDB CRUD operations from a web API
- Customize JSON serialization
View or download sample code (how to download)
Prerequisites
- Visual Studio 2019 with the ASP.NET and web development workload
Configure MongoDB
If using Windows, MongoDB is installed at C:Program FilesMongoDB by default. Add C:Program FilesMongoDBServer<version_number>bin to the Path
environment variable. This change enables MongoDB access from anywhere on your development machine.
Use the mongo Shell in the following steps to create a database, make collections, and store documents. For more information on mongo Shell commands, see Working with the mongo Shell.
Choose a directory on your development machine for storing the data. For example, C:BooksData on Windows. Create the directory if it doesn't exist. The mongo Shell doesn't create new directories.
Open a command shell. Run the following command to connect to MongoDB on default port 27017. Remember to replace
<data_directory_path>
with the directory you chose in the previous step.Open another command shell instance. Connect to the default test database by running the following command:
Run the following in a command shell:
If it doesn't already exist, a database named BookstoreDb is created. If the database does exist, its connection is opened for transactions.
Create a
Books
collection using following command:The following result is displayed:
Define a schema for the
Books
collection and insert two documents using the following command:The following result is displayed:
Note
The ID's shown in this article will not match the IDs when you run this sample.
View the documents in the database using the following command:
The following result is displayed:
The schema adds an autogenerated
_id
property of typeObjectId
for each document.
The database is ready. You can start creating the ASP.NET Core web API.
Create the ASP.NET Core web API project
Go to File > New > Project.
Select the ASP.NET Core Web Application project type, and select Next.
Name the project BooksApi, and select Create.
Select the .NET Core target framework and ASP.NET Core 2.2. Select the API project template, and select Create.
Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. In the Package Manager Console window, navigate to the project root. Run the following command to install the .NET driver for MongoDB:
Run the following commands in a command shell:
A new ASP.NET Core web API project targeting .NET Core is generated and opened in Visual Studio Code.
After the status bar's OmniSharp flame icon turns green, a dialog asks Required assets to build and debug are missing from 'BooksApi'. Add them?. Select Yes.
Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. Open Integrated Terminal and navigate to the project root. Run the following command to install the .NET driver for MongoDB:
- Go to File > New Solution > .NET Core > App.
- Select the ASP.NET Core Web API C# project template, and select Next.
- Select .NET Core 2.2 from the Target Framework drop-down list, and select Next.
- Enter BooksApi for the Project Name, and select Create.
- In the Solution pad, right-click the project's Dependencies node and select Add Packages.
- Enter MongoDB.Driver in the search box, select the MongoDB.Driver package, and select Add Package.
- Select the Accept button in the License Acceptance dialog.
Add an entity model
Add a Models directory to the project root.
Add a
Book
class to the Models directory with the following code:In the preceding class, the
Id
property:- Is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
- Is annotated with [BsonId] to designate this property as the document's primary key.
- Is annotated with [BsonRepresentation(BsonType.ObjectId)] to allow passing the parameter as type
string
instead of an ObjectId structure. Mongo handles the conversion fromstring
toObjectId
.
The
BookName
property is annotated with the [BsonElement] attribute. The attribute's value ofName
represents the property name in the MongoDB collection.
Add a configuration model
Add the following database configuration values to appsettings.json:
Add a BookstoreDatabaseSettings.cs file to the Models directory with the following code:
The preceding
BookstoreDatabaseSettings
class is used to store the appsettings.json file'sBookstoreDatabaseSettings
property values. The JSON and C# property names are named identically to ease the mapping process.Add the following highlighted code to
Startup.ConfigureServices
:In the preceding code:
- The configuration instance to which the appsettings.json file's
BookstoreDatabaseSettings
section binds is registered in the Dependency Injection (DI) container. For example, aBookstoreDatabaseSettings
object'sConnectionString
property is populated with theBookstoreDatabaseSettings:ConnectionString
property in appsettings.json. - The
IBookstoreDatabaseSettings
interface is registered in DI with a singleton service lifetime. When injected, the interface instance resolves to aBookstoreDatabaseSettings
object.
- The configuration instance to which the appsettings.json file's
Add the following code to the top of Startup.cs to resolve the
BookstoreDatabaseSettings
andIBookstoreDatabaseSettings
references:
Add a CRUD operations service
Add a Services directory to the project root.
Add a
BookService
class to the Services directory with the following code:In the preceding code, an
IBookstoreDatabaseSettings
instance is retrieved from DI via constructor injection. This technique provides access to the appsettings.json configuration values that were added in the Add a configuration model section.Add the following highlighted code to
Startup.ConfigureServices
:In the preceding code, the
BookService
class is registered with DI to support constructor injection in consuming classes. The singleton service lifetime is most appropriate becauseBookService
takes a direct dependency onMongoClient
. Per the official Mongo Client reuse guidelines,MongoClient
should be registered in DI with a singleton service lifetime.Add the following code to the top of Startup.cs to resolve the
BookService
reference:
The BookService
class uses the following MongoDB.Driver
members to perform CRUD operations against the database:
MongoClient – Reads the server instance for performing database operations. The constructor of this class is provided the MongoDB connection string:
IMongoDatabase – Represents the Mongo database for performing operations. This tutorial uses the generic GetCollection<TDocument>(collection) method on the interface to gain access to data in a specific collection. Perform CRUD operations against the collection after this method is called. In the
GetCollection<TDocument>(collection)
method call:collection
represents the collection name.TDocument
represents the CLR object type stored in the collection.
GetCollection<TDocument>(collection)
returns a MongoCollection object representing the collection. In this tutorial, the following methods are invoked on the collection:
- DeleteOne – Deletes a single document matching the provided search criteria.
- Find<TDocument> – Returns all documents in the collection matching the provided search criteria.
- InsertOne – Inserts the provided object as a new document in the collection.
- ReplaceOne – Replaces the single document matching the provided search criteria with the provided object.
Add a controller
Add a BooksController
class to the Controllers directory with the following code:
The preceding web API controller:
- Uses the
BookService
class to perform CRUD operations. - Contains action methods to support GET, POST, PUT, and DELETE HTTP requests.
- Calls CreatedAtRoute in the
Create
action method to return an HTTP 201 response. Status code 201 is the standard response for an HTTP POST method that creates a new resource on the server.CreatedAtRoute
also adds aLocation
header to the response. TheLocation
header specifies the URI of the newly created book.
Test the web API
Build and run the app.
Navigate to
http://localhost:<port>/api/books
to test the controller's parameterlessGet
action method. The following JSON response is displayed:Navigate to
http://localhost:<port>/api/books/{id here}
to test the controller's overloadedGet
action method. The following JSON response is displayed:
Configure JSON serialization options
Mongodb For Local Machine
There are two details to change about the JSON responses returned in the Test the web API section:
Mongodb For Machine Learning
- The property names' default camel casing should be changed to match the Pascal casing of the CLR object's property names.
- The
bookName
property should be returned asName
.
To satisfy the preceding requirements, make the following changes:
In
Startup.ConfigureServices
, chain the following highlighted code on to theAddMvc
method call:With the preceding change, property names in the web API's serialized JSON response match their corresponding property names in the CLR object type. For example, the
Book
class'sAuthor
property serializes asAuthor
.In Models/Book.cs, annotate the
BookName
property with the following [JsonProperty] attribute:The
[JsonProperty]
attribute's value ofName
represents the property name in the web API's serialized JSON response.Add the following code to the top of Models/Book.cs to resolve the
[JsonProperty]
attribute reference:Repeat the steps defined in the Test the web API section. Notice the difference in JSON property names.
Add authentication support to a web API
ASP.NET Core Identity adds user interface (UI) login functionality to ASP.NET Core web apps. To secure web APIs and SPAs, use one of the following:
- Azure Active Directory B2C (Azure AD B2C)]
Mongodb Tutorial For Mac
IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core 3.0. IdentityServer4 enables the following security features:
- Authentication as a Service (AaaS)
- Single sign-on/off (SSO) over multiple application types
- Access control for APIs
- Federation Gateway
Install Mongodb For Mac Os
For more information, see Welcome to IdentityServer4.
Next steps
Mongodb Shell For Mac
For more information on building ASP.NET Core web APIs, see the following resources: