sourceName stringclasses 1
value | url stringclasses 20
values | action stringclasses 1
value | body stringlengths 23 1.11k | format stringclasses 1
value | metadata dict | title stringclasses 20
values | updated stringclasses 1
value | embedding listlengths 384 384 |
|---|---|---|---|---|---|---|---|---|
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | # Instant GraphQL APIs for MongoDB with Grafbase
# Instant GraphQL APIs for MongoDB with Grafbase
In the ever-evolving landscape of web development, efficient data management and retrieval are paramount for creating dynamic and responsive applications. MongoDB, a versatile NoSQL database, and GraphQL, a powerful query language for APIs, have emerged as a dynamic duo that empowers developers to build robust, flexible, and high-performance applications.
When combined, MongoDB and GraphQL offer a powerful solution for front-end developers, especially when used at the edge.
You may be curious about the synergy between an unstructured database and a structured query language. Fortunately, Grafbase offers a solution that seamlessly combines both by leveraging its distinctive connector schema transformations.
## Prerequisites
In this tutorial, you’ll see how easy it is to get set up with MongoDB and Grafbase, simplifying the introduction of GraphQL into your applications.
You will need the following to get started: | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.060496795922517776,
-0.013936665840446949,
-0.02468806877732277,
-0.03338273987174034,
0.024320261552929878,
-0.011687575839459896,
-0.023852085694670677,
0.03201303258538246,
-0.027110237628221512,
0.012231258675456047,
0.00724195409566164,
-0.04257605969905853,
0.045680586248636246,
0... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | You will need the following to get started:
- An account with Grafbase
- An account with MongoDB Atlas
- A database with data API access enabled
## Enable data API access
You will need a database with MongoDB Atlas to follow along — create one now!
For the purposes of this tutorial, I’ve created a free shared cluster with a single database deployment. We’ll refer to this instance as your “Data Source” later.
through the `g.datasource(mongodb)` call.
## Create models for data
The MongoDB connector empowers developers to organize their MongoDB collections in a manner that allows Grafbase to autonomously generate the essential queries and mutations for document creation, retrieval, update, and deletion within these collections.
Within Grafbase, each configuration for a collection is referred to as a "model," and you have the flexibility to employ the supported GraphQL Scalars to represent data within the collection(s). | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.03375741466879845,
-0.033944129943847656,
-0.017114445567131042,
-0.017170077189803123,
-0.004807525314390659,
-0.005820518359541893,
0.0037084852810949087,
0.016908280551433563,
-0.0303354412317276,
0.004149143118411303,
0.02710813283920288,
-0.054124634712934494,
0.03268357366323471,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | It's important to consider that in cases where you possess pre-existing documents in your collection, not all fields are applicable to every document.
Let’s work under the assumption that you have no existing documents and want to create a new collection for `users`. Using the Grafbase TypeScript SDK, we can write the schema for each user model. It looks something like this:
```ts
const address = g.type('Address', {
street: g.string().mapped('street_name')
})
mongodb
.model('User', {
name: g.string(),
email: g.string().optional(),
address: g.ref(address)
})
.collection('users')
```
This schema will generate a fully working GraphQL API with queries and mutations as well as all input types for pagination, ordering, and filtering: | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.05429348349571228,
0.013072926551103592,
0.0013313607778400183,
-0.04195773974061012,
0.04100897163152695,
0.010005906224250793,
-0.006218921858817339,
0.012553784996271133,
-0.01156857330352068,
0.013234520331025124,
0.011654912494122982,
-0.043243974447250366,
0.026640960946679115,
0.... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | This schema will generate a fully working GraphQL API with queries and mutations as well as all input types for pagination, ordering, and filtering:
- `userCreate` – Create a new user
- `userCreateMany` – Batch create new users
- `userUpdate` – Update an existing user
- `userUpdateMany` – Batch update users
- `userDelete` – Delete a user
- `userDeleteMany` – Batch delete users
- `user` – Fetch a single user record
- `userCollection` – Fetch multiple users from a collection
MongoDB automatically generates collections when you first store data, so there’s no need to manually create a collection for users at this step.
We’re now ready to start the Grafbase development server using the CLI:
```bash
npx grafbase dev
``` | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.04429103806614876,
0.0030695730820298195,
-0.0010024664225056767,
-0.047095879912376404,
0.020874353125691414,
0.016409657895565033,
0.0023989833425730467,
0.02798275463283062,
-0.019348371773958206,
0.014236866496503353,
0.01740475744009018,
-0.06229391321539879,
0.0627003014087677,
0.... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | We’re now ready to start the Grafbase development server using the CLI:
```bash
npx grafbase dev
```
This command runs the entire Grafbase GraphQL API locally that you can use when developing your front end. The Grafbase API communicates directly with your Atlas Data API.
Once the command is running, you’ll be able to visit http://127.0.0.1:4000 and explore the GraphQL API.
## Insert users with GraphQL to MongoDB instance
Let’s test out creating users inside our MongoDB collection using the generated `userCreate` mutation that was provided to us by Grafbase.
Using Pathfinder at http://127.0.0.1:4000, execute the following mutation: | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.06417394429445267,
-0.02632194757461548,
-0.004139021970331669,
-0.032131195068359375,
0.01252369862049818,
-0.013693425804376602,
0.002537115477025509,
0.02528579719364643,
-0.03510201722383499,
-0.0057494547218084335,
0.02860289067029953,
-0.05519753694534302,
0.04138803854584694,
-0.... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | Using Pathfinder at http://127.0.0.1:4000, execute the following mutation:
```
mutation {
mongo {
userCreate(input: {
name: "Jamie Barton",
email: "jamie@grafbase.com",
age: 40
}) {
insertedId
}
}
}
```
If everything is hooked up correctly, you should see a response that looks something like this:
```json
{
"data": {
"mongo": {
"userCreate": {
"insertedId": "65154a3d4ddec953105be188"
}
}
}
}
```
You should repeat this step a few times to create multiple users.
## Update user by ID
Now we’ve created some users in our MongoDB collection, let’s try updating a user by `insertedId`: | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.06117311865091324,
-0.0031077698804438114,
0.018838027492165565,
-0.026751015335321426,
0.0010560760274529457,
-0.010990395210683346,
0.03595113381743431,
0.00008211717795347795,
-0.027257390320301056,
0.006800724193453789,
0.007833351381123066,
-0.06216532364487648,
0.02361544407904148,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | ## Update user by ID
Now we’ve created some users in our MongoDB collection, let’s try updating a user by `insertedId`:
```
mutation {
mongo {
userUpdate(by: {
id: "65154a3d4ddec953105be188"
}, input: {
age: {
set: 35
}
}) {
modifiedCount
}
}
}
```
Using the `userUpdate` mutation above, we `set` a new `age` value for the user where the `id` matches that of the ObjectID we passed in.
If everything was successful, you should see something like this:
```json
{
"data": {
"mongo": {
"userUpdate": {
"modifiedCount": 1
}
}
}
}
```
## Delete user by ID | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.07056047767400742,
0.023055972531437874,
0.036091845482587814,
-0.03555043786764145,
0.04239572584629059,
-0.024462005123496056,
0.051553357392549515,
0.01875956542789936,
-0.0033555980771780014,
0.014920142479240894,
0.016952769830822945,
-0.045979905873537064,
0.02681058458983898,
0.0... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | ## Delete user by ID
Deleting users is similar to the create and update mutations above, but we don’t need to provide any additional `input` data since we’re deleting only:
```
mutation {
mongo {
userDelete(by: {
id: "65154a3d4ddec953105be188"
}) {
deletedCount
}
}
}
```
If everything was successful, you should see something like this:
```json
{
"data": {
"mongo": {
"userDelete": {
"deletedCount": 1
}
}
}
}
```
## Fetch all users
Grafbase generates the query `userCollection` that you can use to fetch all users. Grafbase requires a `first` or `last` pagination value with a max value of `100`: | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.05340757966041565,
0.022377613931894302,
0.027686472982168198,
-0.02726184017956257,
0.047844938933849335,
-0.02716010808944702,
0.04417137801647186,
0.04182431846857071,
-0.015378356911242008,
0.019935769960284233,
0.013906395994126797,
-0.051592398434877396,
0.047898877412080765,
0.03... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | ```
query {
mongo {
userCollection(first: 100) {
edges {
node {
id
name
email
age
}
}
}
}
}
```
Here we are fetching the `first` 100 users from the collection. You can also pass a filter and order argument to tune the results:
```
query {
mongo {
userCollection(first: 100, filter: {
age: {
gt: 30
}
}, orderBy: {
age: ASC
}) {
edges {
node {
id
name
email
age
}
}
}
}
}
```
## Fetch user by ID
Using the same GraphQL API, we can fetch a user by the object ID. Grafbase automatically generates the query `user` where we can pass the `id` to the `by` input type: | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.043748993426561356,
0.030563896521925926,
-0.003987419418990612,
-0.01940014772117138,
0.01786317117512226,
-0.005038009956479073,
0.028533639386296272,
0.025421829894185066,
-0.008042658679187298,
0.01552485954016447,
-0.004550616722553968,
-0.04388279467821121,
0.049167294055223465,
0... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | ```
query {
mongo {
user(
by: {
id: "64ee1cfbb315482287acea78"
}
) {
id
name
email
age
}
}
}
```
## Enable faster responses with GraphQL Edge Caching
Every request we make so far to our GraphQL API makes a round trip to the MongoDB database. This is fine, but we can improve response times even further by enabling GraphQL Edge Caching for GraphQL queries.
To enable GraphQL Edge Caching, inside `grafbase/grafbase.config.ts`, add the following to the `config` export:
```ts
export default config({
schema: g,
cache: {
rules:
{
types: 'Query',
maxAge: 60
}
]
}
})
``` | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.04972122609615326,
0.02118612453341484,
0.00963200069963932,
0.0016703347209841013,
0.029073672369122505,
-0.023298271000385284,
0.011379036121070385,
0.029985908418893814,
-0.018492111936211586,
-0.009112842381000519,
-0.00013112025044392794,
-0.04699208214879036,
0.04552290216088295,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | This configuration will cache any query. If you only want to disable caching on some collections, you can do that too. [Learn more about GraphQL Edge Caching.
## Deploy to the edge
So far, we’ve been working with Grafbase locally using the CLI, but now it’s time to deploy this around the world to the edge with GitHub.
If you already have an existing GitHub repository, go ahead and commit the changes we’ve made so far. If you don’t already have a GitHub repository, you will need to create one, commit this code, and push it to GitHub.
Now, create a new project with Grafbase and connect your GitHub account. You’ll need to permit Grafbase to read your repository contents, so make sure you select the correct repository and allow that. | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.02148193120956421,
-0.010524870827794075,
0.0006254873587749898,
0.02242985926568508,
-0.0030463174916803837,
-0.030734268948435783,
0.016447149217128754,
0.00230612326413393,
-0.013110250234603882,
-0.013083008117973804,
0.010736558586359024,
-0.020929548889398575,
0.0785050094127655,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | Before you click **Deploy**, make sure to insert the environment variables obtained previously in the tutorial. Grafbase also supports environment variables for preview environments, so if you want to use a different MongoDB database for any Grafbase preview deployment, you can configure that later.
, URQL, and Houdini.
If you have questions or comments, continue the conversation over in the MongoDB Developer Community. | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.032048068940639496,
-0.015040350146591663,
0.02186408080160618,
-0.014235897921025753,
0.046102169901132584,
-0.014689587987959385,
-0.03554341569542885,
0.01145886816084385,
-0.015134288929402828,
0.016420645639300346,
0.022054368630051613,
-0.05332082137465477,
0.04446163401007652,
0.... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | [1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt86a1fb09aa5e51ae/65282bf00749064f73257e71/image6.png
[2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt67f4040e41799bbc/65282c10814c6c262bc93103/image1.png
[3]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt75ca38cd9261e241/65282c30ff3bbd5d44ad0aa3/image4.png | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.03651268780231476,
-0.0050010900013148785,
0.03372596204280853,
-0.00991231482475996,
0.02992740273475647,
0.023926256224513054,
-0.007598471827805042,
0.023347225040197372,
-0.003810047172009945,
-0.023885449394583702,
0.01655525341629982,
-0.08948531746864319,
0.028514496982097626,
0.... |
devcenter | https://www.mongodb.com/developer/products/atlas/instant-graphql-apis-mongodb-grafbase | created | [4]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltaf2a2af39e731dbe/65282c54391807638d3b0e1d/image5.png
[5]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt0c9563b3fdbf34fd/65282c794824f57358f273cf/image3.png
[6]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt731c99011d158491/65282ca631f9bbb92a9669ad/image2.png | md | {
"tags": [
"Atlas",
"TypeScript",
"GraphQL"
],
"pageDescription": "Learn how to quickly and easily create a GraphQL API from your MongoDB data with Grafbase.",
"contentType": "Tutorial"
} | Instant GraphQL APIs for MongoDB with Grafbase | 2024-05-20T17:32:23.500Z | [
-0.032542746514081955,
0.0026832344010472298,
0.026951320469379425,
-0.02318979799747467,
0.031845156103372574,
0.010651635006070137,
-0.0010173850459977984,
0.011552304960787296,
-0.0025988540146499872,
-0.026464473456144333,
0.029528485611081123,
-0.07951211929321289,
0.032484155148267746,... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | # Exploring Window Operators in Atlas Stream Processing
> Atlas Stream Processing is now available. Learn more about it here.
In our previous post on windowing, we introduced window operators available in Atlas Stream Processing. Window operators are one of the most commonly used operations to effectively process streaming data. Atlas Stream Processing provides two window operators: $tumblingWindow and $hoppingWindow. In this tutorial, we will explore both of these operators using the sample solar data generator provided within Atlas Stream Processing.
## Getting started
Before we begin creating stream processors, make sure you have a database user who has “atlasAdmin” access to the Atlas Project. Also, if you do not already have a Stream Processing Instance created with a connection to the sample_stream_solar data generator, please follow the instructions in Get Started with Atlas Stream Processing: Creating Your First Stream Processor and then continue on.
## View the solar stream sample data | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.048927512019872665,
-0.003921780269593,
0.04130646586418152,
-0.004971460439264774,
0.017873959615826607,
0.0039832135662436485,
0.04579886049032211,
-0.015007194131612778,
-0.0012598464963957667,
-0.02444789744913578,
-0.009361923672258854,
-0.04687841609120369,
-0.019811274483799934,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ## View the solar stream sample data
For this tutorial, we will be using the MongoDB shell.
First, confirm sample_stream_solar is added as a connection by issuing `sp.listConnections()`.
```
AtlasStreamProcessing> sp.listConnections()
{
ok: 1,
connections:
{
name: 'sample_stream_solar',
type: 'inmemory',
createdAt: ISODate("2023-08-26T18:42:48.357Z")
}
]
}
```
Next, let’s define a **$source** stage to describe where Atlas Stream Processing will read the stream data from.
```
var solarstream={ $source: { "connectionName": "sample_stream_solar" } }
```
Then, issue a **.process** command to view the contents of the stream on the console.
```
sp.process([solarstream])
``` | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.05985584482550621,
0.011241280473768711,
0.01399822998791933,
-0.02559373527765274,
0.024506209418177605,
-0.024106847122311592,
0.04378458485007286,
-0.013441276736557484,
-0.025579752400517464,
-0.01239199098199606,
0.0058982293121516705,
-0.040709663182497025,
-0.017621947452425957,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ```
sp.process([solarstream])
```
You will see the stream of solar data printed on the console. A sample of this data is as follows:
```json
{
device_id: 'device_2',
group_id: 3,
timestamp: '2023-08-27T13:51:53.375+00:00',
max_watts: 250,
event_type: 0,
obs: {
watts: 168,
temp: 15
},
_ts: ISODate("2023-08-27T13:51:53.375Z"),
_stream_meta: {
sourceType: 'sampleData',
timestamp: ISODate("2023-08-27T13:51:53.375Z")
}
}
```
## Create a tumbling window query | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.04297640919685364,
0.012074882164597511,
0.027006974443793297,
-0.02037661150097847,
0.0616239532828331,
-0.04768279194831848,
0.05545692890882492,
-0.02141115628182888,
0.037646740674972534,
0.00899985060095787,
-0.006340178195387125,
-0.07149219512939453,
-0.013234755024313927,
0.0064... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ## Create a tumbling window query
A tumbling window is a fixed-size window that moves forward in time at regular intervals. In Atlas Stream Processing, you use the [$tumblingWindow operator. In this example, let’s use the operator to compute the average watts over one-minute intervals.
Refer back to the schema from the sample stream solar data. To create a tumbling window, let’s create a variable and define our tumbling window stage.
```javascript
var Twindow= {
$tumblingWindow: {
interval: { size: NumberInt(1), unit: "minute" },
pipeline:
{
$group: {
_id: "$device_id",
max: { $max: "$obs.watts" },
avg: { $avg: "$obs.watts" }
}
}
]
}
}
``` | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.0490262396633625,
-0.0163712240755558,
0.03372541069984436,
0.010498758405447006,
0.01721784844994545,
-0.0047952551394701,
0.023109519854187965,
-0.020730765536427498,
0.03215262293815613,
-0.023619646206498146,
-0.02630598656833172,
-0.046467944979667664,
-0.0013564852997660637,
-0.00... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | We are calculating the maximum value and average over the span of one-minute, non-overlapping intervals. Let’s use the `.process` command to run the streaming query in the foreground and view our results in the console.
```
sp.process([solarstream,Twindow])
```
Here is an example output of the statement: | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.08582590520381927,
-0.017711130902171135,
0.02370045706629753,
-0.038152217864990234,
0.02320169284939766,
-0.031578607857227325,
0.04338984936475754,
-0.008935372345149517,
0.05619140341877937,
0.002810732927173376,
0.029374748468399048,
-0.0434701107442379,
-0.013165724463760853,
0.02... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | Here is an example output of the statement:
```json
{
_id: 'device_4',
max: 236,
avg: 95,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T13:59:00.000Z"),
windowEndTimestamp: ISODate("2023-08-27T14:00:00.000Z")
}
}
{
_id: 'device_2',
max: 211,
avg: 117.25,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T13:59:00.000Z"),
windowEndTimestamp: ISODate("2023-08-27T14:00:00.000Z")
}
}
```
## Exploring the window operator pipeline | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.06474524736404419,
0.018204856663942337,
0.04410383105278015,
-0.023478558287024498,
0.05389182269573212,
-0.017676012590527534,
0.035181980580091476,
0.004596846178174019,
0.0043223244138062,
0.0188174769282341,
-0.03164099529385567,
-0.05980885401368141,
-0.0036178804002702236,
0.0118... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ## Exploring the window operator pipeline
The pipeline that is used within a window function can include blocking stages and non-blocking stages.
[Accumulator operators such as `$avg`, `$count`, `$sort`, and `$limit` can be used within blocking stages. Meaningful data returned from these operators are obtained when run over a series of data versus a single data point. This is why they are considered blocking. | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.0676313042640686,
-0.021568244323134422,
0.032407741993665695,
-0.030507676303386688,
-0.008578830398619175,
0.0313553623855114,
0.04627580568194389,
0.010022683069109917,
0.0404842309653759,
-0.0068512349389493465,
-0.03195171430706978,
-0.02525431290268898,
0.018437296152114868,
0.005... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | Non-blocking stages do not require multiple data points to be meaningful, and they include operators such as `$addFields`, `$match`, `$project`, `$set`, `$unset`, and `$unwind`, to name a few. You can use non-blocking before, after, or within the blocking stages. To illustrate this, let’s create a query that shows the average, maximum, and delta (the difference between the maximum and average). We will use a non-blocking **$match** to show only the results from device_1, calculate the tumblingWindow showing maximum and average, and then include another non-blocking `$addFields`.
```
var m= { '$match': { device_id: 'device_1' } }
``` | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.08450532704591751,
-0.012346778996288776,
0.03441380709409714,
-0.03814255818724632,
0.022254062816500664,
0.021236564964056015,
0.0389101505279541,
-0.0034526961389929056,
0.03986368700861931,
0.002080135280266404,
0.0027994918636977673,
0.0005163490423001349,
0.008730844594538212,
0.0... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ```
var m= { '$match': { device_id: 'device_1' } }
```
```javascript
var Twindow= {
'$tumblingWindow': {
interval: { size: Int32(1), unit: 'minute' },
pipeline:
{
'$group': {
_id: '$device_id',
max: { '$max': '$obs.watts' },
avg: { '$avg': '$obs.watts' }
}
}
]
}
}
var delta = { '$addFields': { delta: { '$subtract': ['$max', '$avg'] } } }
```
Now we can use the .process command to run the stream processor in the foreground and view our results in the console.
```
sp.process([solarstream,m,Twindow,delta])
```
The results of this query will be similar to the following: | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.063898965716362,
-0.01814083382487297,
0.018315494060516357,
-0.015645993873476982,
0.03153586387634277,
-0.04198445752263069,
0.038139116019010544,
-0.02579423598945141,
0.0072005270048975945,
-0.007976210676133633,
-0.021708112210035324,
-0.04116220772266388,
-0.0051348283886909485,
-... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ```json
{
_id: 'device_1',
max: 238,
avg: 75.3,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T19:11:00.000Z"),
windowEndTimestamp: ISODate("2023-08-27T19:12:00.000Z")
},
delta: 162.7
}
{
_id: 'device_1',
max: 220,
avg: 125.08333333333333,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T19:12:00.000Z"), | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.04073255509138107,
0.0042763929814100266,
0.052308134734630585,
-0.03382594510912895,
0.07465413212776184,
-0.022355614230036736,
0.00898932944983244,
0.00878862850368023,
-0.009247039444744587,
0.028960295021533966,
-0.008399355225265026,
-0.07872101664543152,
-0.0051200417801737785,
0... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | windowStartTimestamp: ISODate("2023-08-27T19:12:00.000Z"),
windowEndTimestamp: ISODate("2023-08-27T19:13:00.000Z")
},
delta: 94.91666666666667
}
{
_id: 'device_1',
max: 238,
avg: 119.91666666666667,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T19:13:00.000Z"),
windowEndTimestamp: ISODate("2023-08-27T19:14:00.000Z")
},
delta: 118.08333333333333
}
``` | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.04192350059747696,
0.005057218950241804,
0.04776932671666145,
-0.03538205847144127,
0.06215778738260269,
-0.018820492550730705,
0.010022841393947601,
0.008382371626794338,
0.008181197568774223,
0.0186147503554821,
0.016939347609877586,
-0.07109034061431885,
-0.0025426147039979696,
0.013... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | Notice the time segments and how they align on the minute.
![Time segments aligned on the minute][1]
Additionally, notice that the output includes the difference between the calculated values of maximum and average for each window.
## Create a hopping window
A hopping window, sometimes referred to as a sliding window, is a fixed-size window that moves forward in time at overlapping intervals. In Atlas Stream Processing, you use the `$hoppingWindow` operator. In this example, let’s use the operator to see the average. | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.07166609913110733,
-0.021013671532273293,
0.04947468638420105,
-0.006552341394126415,
0.019174879416823387,
0.03226522356271744,
0.04914402216672897,
-0.018224550411105156,
0.03693750500679016,
-0.01090160571038723,
-0.0012216155882924795,
-0.02683074213564396,
0.001475909142754972,
0.0... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ```javascript
var Hwindow = {
'$hoppingWindow': {
interval: { size: 1, unit: 'minute' },
hopSize: { size: 30, unit: 'second' },
pipeline: [
{
'$group': {
_id: '$device_id',
max: { '$max': '$obs.watts' },
avg: { '$avg': '$obs.watts' }
}
}
]
}
}
```
To help illustrate the start and end time segments, let's create a filter to only return device_1.
```
var m = { '$match': { device_id: 'device_1' } }
```
Now let’s issue the `.process` command to view the results in the console.
```
sp.process([solarstream,m,Hwindow])
```
An example result is as follows: | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.07824836671352386,
-0.006098929792642593,
0.04394914209842682,
-0.044625137001276016,
0.036681368947029114,
-0.023785656318068504,
0.037727102637290955,
-0.014739811420440674,
0.02055465616285801,
-0.01616945117712021,
-0.011969096027314663,
-0.03755716606974602,
-0.0033204667270183563,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | ```json
{
_id: 'device_1',
max: 238,
avg: 76.625,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T19:37:30.000Z"),
windowEndTimestamp: ISODate("2023-08-27T19:38:30.000Z")
}
}
{
_id: 'device_1',
max: 238,
avg: 82.71428571428571,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T19:38:00.000Z"), | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.04295774921774864,
0.0006684493855573237,
0.05419166386127472,
-0.038589153438806534,
0.07302572578191757,
-0.022559432312846184,
0.011814754456281662,
0.017255695536732674,
-0.009724478237330914,
0.029542602598667145,
-0.006891238037496805,
-0.08086171746253967,
-0.005541868042200804,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | windowStartTimestamp: ISODate("2023-08-27T19:38:00.000Z"),
windowEndTimestamp: ISODate("2023-08-27T19:39:00.000Z")
}
}
{
_id: 'device_1',
max: 220,
avg: 105.54545454545455,
_stream_meta: {
sourceType: 'sampleData',
windowStartTimestamp: ISODate("2023-08-27T19:38:30.000Z"),
windowEndTimestamp: ISODate("2023-08-27T19:39:30.000Z")
}
}
``` | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.047265421599149704,
0.001993212616071105,
0.03947646915912628,
-0.03295068070292473,
0.05066690221428871,
-0.013895689509809017,
0.011128689162433147,
0.007951563224196434,
0.00411618547514081,
0.015802815556526184,
0.021963506937026978,
-0.07337607443332672,
0.0031348394695669413,
0.01... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | Notice the time segments.
![Overlapping time segments][2]
The time segments are overlapping by 30 seconds as was defined by the hopSize option. Hopping windows are useful to capture short-term patterns in data.
## Summary
By continuously processing data within time windows, you can generate real-time insights and metrics, which can be crucial for applications like monitoring, fraud detection, and operational analytics. Atlas Stream Processing provides both tumbling and hopping window operators. Together these operators enable you to perform various aggregation operations such as sum, average, min, and max over a specific window of data. In this tutorial, you learned how to use both of these operators with solar sample data.
### Learn more about MongoDB Atlas Stream Processing
Check out the [MongoDB Atlas Stream Processing announcement blog post. For more on window operators in Atlas Stream Processing, learn more in our documentation. | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.05368148908019066,
-0.005898487754166126,
0.042008090764284134,
-0.018526144325733185,
0.03428162634372711,
0.00844896025955677,
0.05682070180773735,
-0.02843351848423481,
0.022768769413232803,
-0.016144035384058952,
-0.0005389516591094434,
-0.034369248896837234,
0.0018051794031634927,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/exploring-window-operators-atlas-stream-processing | created | >Log in today to get started. Atlas Stream Processing is available to all developers in Atlas. Give it a try today!
[1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt73ff54f0367cad3b/650da3ef69060a5678fc1242/image1.jpg
[2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt833bc1a824472d14/650da41aa5f15dea3afc5b55/image3.jpg | md | {
"tags": [
"Atlas"
],
"pageDescription": "Learn how to use the various window operators such as tumbling window and hopping window with MongoDB Atlas Stream Processing.",
"contentType": "Tutorial"
} | Exploring Window Operators in Atlas Stream Processing | 2024-05-20T17:32:23.500Z | [
-0.011378276161849499,
-0.01672467216849327,
0.020003018900752068,
-0.040189094841480255,
-0.008565499447286129,
0.010022525675594807,
-0.00259906193241477,
-0.0034882749896496534,
-0.019957955926656723,
-0.04163186252117157,
0.029949022457003593,
-0.08186767995357513,
-0.024198634549975395,... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | # Getting Started with MongoDB and FastAPI
FastAPI is a modern, high-performance, easy-to-learn, fast-to-code, production-ready, Python 3.6+ framework for building APIs based on standard Python type hints. While it might not be as established as some other Python frameworks such as Django, it is already in production at companies such as Uber, Netflix, and Microsoft.
FastAPI is async, and as its name implies, it is super fast; so, MongoDB is the perfect accompaniment. In this quick start, we will create a CRUD (Create, Read, Update, Delete) app showing how you can integrate MongoDB with your FastAPI projects.
## Prerequisites
- Python 3.9.0
- A MongoDB Atlas cluster. Follow the "Get Started with Atlas" guide to create your account and MongoDB cluster. Keep a note of your username, password, and connection string as you will need those later. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.08094657212495804,
-0.01399584487080574,
-0.01831529662013054,
-0.00742050725966692,
0.025800786912441254,
-0.028907081112265587,
0.0032158594112843275,
-0.021332303062081337,
-0.0046873935498297215,
-0.0030043884180486202,
0.03144683688879013,
-0.0724397674202919,
0.037368737161159515,
... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | ## Running the Example
To begin, you should clone the example code from GitHub.
``` shell
git clone git@github.com:mongodb-developer/mongodb-with-fastapi.git
```
You will need to install a few dependencies: FastAPI, Motor, etc. I always recommend that you install all Python dependencies in a virtualenv for the project. Before running pip, ensure your virtualenv is active.
``` shell
cd mongodb-with-fastapi
pip install -r requirements.txt
```
It may take a few moments to download and install your dependencies. This is normal, especially if you have not installed a particular package before.
Once you have installed the dependencies, you need to create an environment variable for your MongoDB connection string.
``` shell
export MONGODB_URL="mongodb+srv://:@/?retryWrites=true&w=majority"
``` | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.06842947006225586,
-0.01364817377179861,
0.013708416372537613,
-0.04137702286243439,
0.032189372926950455,
-0.06256020069122314,
-0.013447193428874016,
-0.007026028353720903,
-0.014803295955061913,
-0.010356332175433636,
0.007446484174579382,
-0.07129909843206406,
0.040027979761362076,
... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | ``` shell
export MONGODB_URL="mongodb+srv://:@/?retryWrites=true&w=majority"
```
Remember, anytime you start a new terminal session, you will need to set this environment variable again. I use direnv to make this process easier.
The final step is to start your FastAPI server.
``` shell
uvicorn app:app --reload
```
Once the application has started, you can view it in your browser at .
Once you have had a chance to try the example, come back and we will walk through the code.
## Creating the Application
All the code for the example application is within `app.py`. I'll break it down into sections and walk through what each is doing.
### Connecting to MongoDB
One of the very first things we do is connect to our MongoDB database. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.07526013255119324,
-0.03035750240087509,
-0.004864227958023548,
-0.05822206661105156,
0.03205810859799385,
-0.04861610382795334,
0.004985445644706488,
-0.02333456091582775,
-0.004641909617930651,
-0.015153534710407257,
0.008255629800260067,
-0.05333547294139862,
0.049077633768320084,
0.... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | ### Connecting to MongoDB
One of the very first things we do is connect to our MongoDB database.
``` python
client = motor.motor_asyncio.AsyncIOMotorClient(os.environ"MONGODB_URL"])
db = client.get_database("college")
student_collection = db.get_collection("students")
```
We're using the async [motor driver to create our MongoDB client, and then we specify our database name `college`.
### The \_id Attribute and ObjectIds
``` python
# Represents an ObjectId field in the database.
# It will be represented as a `str` on the model so that it can be serialized to JSON.
PyObjectId = Annotatedstr, BeforeValidator(str)]
``` | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.050679922103881836,
0.010029176250100136,
0.007451031822711229,
-0.030612986534833908,
-0.004811773542314768,
-0.01905105821788311,
0.027533920481801033,
0.040911827236413956,
0.00687057850882411,
0.0006547385710291564,
-0.03031894937157631,
-0.06492987275123596,
0.04173240438103676,
0.... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | MongoDB stores data as [BSON. FastAPI encodes and decodes data as JSON strings. BSON has support for additional non-JSON-native data types, including `ObjectId` which can't be directly encoded as JSON. Because of this, we convert `ObjectId`s to strings before storing them as the `id` field.
### Database Models
Many people think of MongoDB as being schema-less, which is wrong. MongoDB has a flexible schema. That is to say that collections do not enforce document structure by default, so you have the flexibility to make whatever data-modelling choices best match your application and its performance requirements. So, it's not unusual to create models when working with a MongoDB database. Our application has three models, the `StudentModel`, the `UpdateStudentModel`, and the `StudentCollection`.
``` python
class StudentModel(BaseModel):
"""
Container for a single student record.
""" | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.036785420030355453,
-0.0014439199585467577,
0.01233137957751751,
-0.033406928181648254,
0.03540828078985214,
-0.039402998983860016,
-0.0024045882746577263,
0.010649129748344421,
-0.014845358207821846,
0.0029708321671932936,
-0.01446025725454092,
-0.042816996574401855,
0.04882654920220375,... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | # The primary key for the StudentModel, stored as a `str` on the instance.
# This will be aliased to `_id` when sent to MongoDB,
# but provided as `id` in the API requests and responses.
id: OptionalPyObjectId] = Field(alias="_id", default=None)
name: str = Field(...)
email: EmailStr = Field(...)
course: str = Field(...)
gpa: float = Field(..., le=4.0)
model_config = ConfigDict(
populate_by_name=True,
arbitrary_types_allowed=True,
json_schema_extra={
"example": {
"name": "Jane Doe",
"email": "jdoe@example.com",
"course": "Experiments, Science, and Fashion in Nanophotonics",
"gpa": 3.0,
}
},
)
``` | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.015744293108582497,
0.0016902508214116096,
0.03213263303041458,
-0.03782307356595993,
0.02278633415699005,
-0.01970590278506279,
0.0268529262393713,
0.040025077760219574,
0.013490216806530952,
-0.015486675314605236,
0.0005250097019597888,
-0.08670513331890106,
0.03140686824917793,
0.025... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | This is the primary model we use as the [response model for the majority of our endpoints.
I want to draw attention to the `id` field on this model. MongoDB uses `_id`, but in Python, underscores at the start of attributes have special meaning. If you have an attribute on your model that starts with an underscore, pydantic—the data validation framework used by FastAPI—will assume that it is a private variable, meaning you will not be able to assign it a value! To get around this, we name the field `id` but give it an alias of `_id`. You also need to set `populate_by_name` to `True` in the model's `model_config`
We set this `id` value automatically to `None`, so you do not need to supply it when creating a new student. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.04247277230024338,
0.002603664994239807,
0.01781989261507988,
-0.011398901231586933,
0.02709372155368328,
-0.015862761065363884,
0.06356722861528397,
0.012980454601347446,
0.012753420509397984,
-0.016897467896342278,
0.02297328971326351,
-0.1002793237566948,
0.034461721777915955,
0.0210... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | We set this `id` value automatically to `None`, so you do not need to supply it when creating a new student.
``` python
class UpdateStudentModel(BaseModel):
"""
A set of optional updates to be made to a document in the database.
"""
name: Optionalstr] = None
email: Optional[EmailStr] = None
course: Optional[str] = None
gpa: Optional[float] = None
model_config = ConfigDict(
arbitrary_types_allowed=True,
json_encoders={ObjectId: str},
json_schema_extra={
"example": {
"name": "Jane Doe",
"email": "jdoe@example.com",
"course": "Experiments, Science, and Fashion in Nanophotonics",
"gpa": 3.0,
}
},
)
``` | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.03978297859430313,
-0.0038998958189040422,
0.03113911673426628,
-0.042411260306835175,
0.02054752968251705,
0.026125699281692505,
0.013772533275187016,
0.04906705766916275,
0.0054968069307506084,
-0.005620562005788088,
0.023325113579630852,
-0.06093455106019974,
0.027453947812318802,
0.... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | The `UpdateStudentModel` has two key differences from the `StudentModel`:
- It does not have an `id` attribute as this cannot be modified.
- All fields are optional, so you only need to supply the fields you wish to update.
Finally, `StudentCollection` is defined to encapsulate a list of `StudentModel` instances. In theory, the endpoint could return a top-level list of StudentModels, but there are some vulnerabilities associated with returning JSON responses with top-level lists.
```python
class StudentCollection(BaseModel):
"""
A container holding a list of `StudentModel` instances.
This exists because providing a top-level array in a JSON response can be a [vulnerability
"""
students: ListStudentModel]
```
### Application Routes
Our application has five routes: | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.06129203364253044,
-0.031690631061792374,
0.07336078584194183,
-0.02322508953511715,
0.01382946502417326,
-0.01076928898692131,
-0.014039653353393078,
0.0550353042781353,
-0.00840585958212614,
0.003970395773649216,
0.024494195356965065,
-0.06527848541736603,
0.018851755186915398,
0.0224... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | students: ListStudentModel]
```
### Application Routes
Our application has five routes:
- POST /students/ - creates a new student.
- GET /students/ - view a list of all students.
- GET /students/{id} - view a single student.
- PUT /students/{id} - update a student.
- DELETE /students/{id} - delete a student.
#### Create Student Route
``` python
@app.post(
"/students/",
response_description="Add new student",
response_model=StudentModel,
status_code=status.HTTP_201_CREATED,
response_model_by_alias=False,
)
async def create_student(student: StudentModel = Body(...)):
"""
Insert a new student record. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.05035531148314476,
-0.023272689431905746,
0.05021994933485985,
-0.03733350709080696,
-0.012861769646406174,
-0.002017427235841751,
0.0109634380787611,
0.030082829296588898,
0.028843844309449196,
0.02689547836780548,
0.021831469610333443,
-0.06060954928398132,
0.02382783591747284,
0.0422... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | A unique `id` will be created and provided in the response.
"""
new_student = await student_collection.insert_one(
student.model_dump(by_alias=True, exclude=["id"])
)
created_student = await student_collection.find_one(
{"_id": new_student.inserted_id}
)
return created_student
```
The `create_student` route receives the new student data as a JSON string in a `POST` request. We have to decode this JSON request body into a Python dictionary before passing it to our MongoDB client.
The `insert_one` method response includes the `_id` of the newly created student (provided as `id` because this endpoint specifies `response_model_by_alias=False` in the `post` decorator call. After we insert the student into our collection, we use the `inserted_id` to find the correct document and return this in our `JSONResponse`. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.04479850083589554,
0.010139931924641132,
0.03931158781051636,
-0.008711033500730991,
-0.02367403544485569,
-0.008504027500748634,
0.04167981445789337,
0.038248512893915176,
0.007574561517685652,
0.017758511006832123,
0.025114968419075012,
-0.055452559143304825,
0.004346201196312904,
0.0... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | FastAPI returns an HTTP `200` status code by default; but in this instance, a `201` created is more appropriate.
##### Read Routes
The application has two read routes: one for viewing all students and the other for viewing an individual student.
``` python
@app.get(
"/students/",
response_description="List all students",
response_model=StudentCollection,
response_model_by_alias=False,
)
async def list_students():
"""
List all of the student data in the database.
The response is unpaginated and limited to 1000 results.
"""
return StudentCollection(students=await student_collection.find().to_list(1000))
```
Motor's `to_list` method requires a max document count argument. For this example, I have hardcoded it to `1000`; but in a real application, you would use the [skip and limit parameters in `find` to paginate your results. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.08843803405761719,
-0.012546289712190628,
0.006548120640218258,
-0.013807214796543121,
0.006571369711309671,
-0.0006667625275440514,
0.0026781607884913683,
0.023186706006526947,
0.016790403053164482,
0.035735711455345154,
0.06728202849626541,
-0.04253337159752846,
0.04577231779694557,
0... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | ``` python
@app.get(
"/students/{id}",
response_description="Get a single student",
response_model=StudentModel,
response_model_by_alias=False,
)
async def show_student(id: str):
"""
Get the record for a specific student, looked up by `id`.
"""
if (
student := await student_collection.find_one({"_id": ObjectId(id)})
) is not None:
return student
raise HTTPException(status_code=404, detail=f"Student {id} not found")
```
The student detail route has a path parameter of `id`, which FastAPI passes as an argument to the `show_student` function. We use the `id` to attempt to find the corresponding student in the database. The conditional in this section is using an assignment expression, an addition to Python 3.8 and often referred to by the cute sobriquet "walrus operator." | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.05271805450320244,
-0.020202862098813057,
0.027271287515759468,
0.0033538551069796085,
0.00918623898178339,
-0.009227155707776546,
0.05800343304872513,
0.023984309285879135,
0.021717699244618416,
0.014004060067236423,
0.019657155498862267,
-0.06508216261863708,
0.04738813266158104,
0.04... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | If a document with the specified `_id` does not exist, we raise an `HTTPException` with a status of `404`.
##### Update Route
``` python
@app.put(
"/students/{id}",
response_description="Update a student",
response_model=StudentModel,
response_model_by_alias=False,
)
async def update_student(id: str, student: UpdateStudentModel = Body(...)):
"""
Update individual fields of an existing student record.
Only the provided fields will be updated.
Any missing or `null` fields will be ignored.
"""
student = {
k: v for k, v in student.model_dump(by_alias=True).items() if v is not None
} | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.058181606233119965,
-0.022254060953855515,
0.07874832302331924,
0.00841868668794632,
0.015794651582837105,
0.014692680910229683,
-0.032130129635334015,
0.05233578383922577,
-0.008255082182586193,
0.0064775641076266766,
0.0390380434691906,
-0.05819912254810333,
0.05646508187055588,
0.055... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | if len(student) >= 1:
update_result = await student_collection.find_one_and_update(
{"_id": ObjectId(id)},
{"$set": student},
return_document=ReturnDocument.AFTER,
)
if update_result is not None:
return update_result
else:
raise HTTPException(status_code=404, detail=f"Student {id} not found")
# The update is empty, but we should still return the matching document:
if (existing_student := await student_collection.find_one({"_id": id})) is not None:
return existing_student
raise HTTPException(status_code=404, detail=f"Student {id} not found")
``` | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.07646340131759644,
-0.003919348120689392,
0.053970757871866226,
-0.0025844797492027283,
0.027997590601444244,
0.02127731963992119,
0.01200995221734047,
0.03355879709124565,
0.024608004838228226,
-0.00607854500412941,
0.018509235233068466,
-0.06335566192865372,
0.0245219673961401,
0.0401... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | raise HTTPException(status_code=404, detail=f"Student {id} not found")
```
The `update_student` route is like a combination of the `create_student` and the `show_student` routes. It receives the `id` of the document to update as well as the new data in the JSON body. We don't want to update any fields with empty values; so, first of all, we iterate over all the items in the received dictionary and only add the items that have a value to our new document.
If, after we remove the empty values, there are no fields left to update, we instead look for an existing record that matches the `id` and return that unaltered. However, if there are values to update, we use find_one_and_update to $set the new values, and then return the updated document. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.08804577589035034,
-0.01666226051747799,
0.07870104908943176,
-0.000939752149861306,
0.030516302213072777,
0.020044341683387756,
-0.011871187016367912,
0.04733797162771225,
0.0004857280873693526,
0.02439991384744644,
0.03992502763867378,
-0.03405192494392395,
0.03859996050596237,
0.0514... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | If we get to the end of the function and we have not been able to find a matching document to update or return, then we raise a `404` error again.
##### Delete Route
``` python
@app.delete("/students/{id}", response_description="Delete a student")
async def delete_student(id: str):
"""
Remove a single student record from the database.
"""
delete_result = await student_collection.delete_one({"_id": ObjectId(id)})
if delete_result.deleted_count == 1:
return Response(status_code=status.HTTP_204_NO_CONTENT)
raise HTTPException(status_code=404, detail=f"Student {id} not found")
``` | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.07902371138334274,
-0.022844312712550163,
0.06813357025384903,
0.003139766165986657,
0.022486504167318344,
-0.008440575562417507,
-0.0029992079362273216,
0.05096238851547241,
0.02531137317419052,
0.0009535376448184252,
0.035373736172914505,
-0.0512123741209507,
0.058998048305511475,
0.0... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | raise HTTPException(status_code=404, detail=f"Student {id} not found")
```
Our final route is `delete_student`. Again, because this is acting upon a single document, we have to supply an `id` in the URL. If we find a matching document and successfully delete it, then we return an HTTP status of `204` or "No Content." In this case, we do not return a document as we've already deleted it! However, if we cannot find a student with the specified `id`, then instead we return a `404`.
## Our New FastAPI App Generator
If you're excited to build something more production-ready with FastAPI, React & MongoDB, head over to the Github repository for our new FastAPI app generator and start transforming your web development experience.
## Wrapping Up | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.062126949429512024,
-0.013828318566083908,
0.040117502212524414,
0.0020532135386019945,
0.02998032420873642,
0.0006066916394047439,
-0.011185038834810257,
0.055585168302059174,
-0.010046875104308128,
0.007376098074018955,
0.053599026054143906,
-0.031491201370954514,
0.07071076333522797,
... |
devcenter | https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi | created | ## Wrapping Up
I hope you have found this introduction to FastAPI with MongoDB useful. If you would like to learn more, check out my post introducing the FARM stack (FastAPI, React and MongoDB) as well as the FastAPI documentation and this awesome list.
>If you have questions, please head to our developer community website where MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB. | md | {
"tags": [
"Python",
"MongoDB",
"Django",
"FastApi"
],
"pageDescription": "Getting started with MongoDB and FastAPI",
"contentType": "Quickstart"
} | Getting Started with MongoDB and FastAPI | 2024-05-20T17:32:23.500Z | [
-0.07101202756166458,
0.017700325697660446,
-0.008951045572757721,
-0.002964386250823736,
0.046981945633888245,
-0.041667379438877106,
0.016372691839933395,
0.004191009793430567,
-0.006941914092749357,
-0.006653723306953907,
0.01128230057656765,
-0.0520976297557354,
0.06283412128686905,
0.... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | # How to Deploy MongoDB Atlas with AWS CloudFormation
MongoDB Atlas is the multi-cloud developer data platform that provides an integrated suite of cloud database and data services. We help to accelerate and simplify how you build resilient and performant global applications on the cloud provider of your choice.
AWS CloudFormation lets you model, provision, and manage AWS and third-party resources like MongoDB Atlas by treating infrastructure as code (IaC). CloudFormation templates are written in either JSON or YAML.
While there are multiple ways to use CloudFormation to provision and manage your Atlas clusters, such as with Partner Solution Deployments or the AWS CDK, today we’re going to go over how to create your first YAML CloudFormation templates to deploy Atlas clusters with CloudFormation. | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.050000738352537155,
-0.06382527947425842,
0.009798458777368069,
-0.006723190192133188,
0.04475439339876175,
0.011174911633133888,
-0.016620002686977386,
-0.0016239485703408718,
-0.03084622137248516,
-0.011253193952143192,
0.004472709260880947,
-0.057009682059288025,
0.02297678217291832,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | These pre-made templates directly leverage MongoDB Atlas resources from the CloudFormation Public Registry and execute via the AWS CLI/AWS Management Console. Using these is best for users who seek to be tightly integrated into AWS with fine-grained access controls.
Let’s get started!
*Prerequisites:*
- Install and configure an AWS Account and the AWS CLI.
- Install and configure the MongoDB Atlas CLI (optional but recommended).
## Step 1: Create a MongoDB Atlas account
Sign up for a free MongoDB Atlas account, verify your email address, and log into your new account.
Already have an AWS account? Atlas supports paying for usage via the AWS Marketplace (AWS MP) without any upfront commitment — simply sign up for MongoDB Atlas via AWS Marketplace.
and contact AWS support directly, who can help confirm the CIDR range to be used in your Atlas PAK IP Whitelist.
on MongoDB Atlas. | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.04774578660726547,
-0.05048114061355591,
-0.0001565893180668354,
0.009149537421762943,
0.00004828570308745839,
0.008926029317080975,
0.0212631206959486,
-0.0011259728344157338,
0.0017904330743476748,
-0.015232358127832413,
0.018078532069921494,
-0.05467306077480316,
0.036294467747211456,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | on MongoDB Atlas.
). You can set this up with AWS IAM (Identity and Access Management). You can find that in the navigation bar of your AWS. You can find the ARN in the user information in the “Roles” button. Once there, find the role whose ARN you want to use and add it to the Extension Details in CloudFormation. Learn how to create user roles/permissions in the IAM.
required from our GitHub repo. It’s important that you use an ARN with sufficient permissions each time it’s asked for.
.
## Step 7: Deploy the CloudFormation template
In the AWS management console, go to the CloudFormation tab. Then, in the left-hand navigation, click on “Stacks.” In the window that appears, hit the “Create Stack” drop-down. Select “Create new stack with existing resources.” | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.0755174532532692,
-0.045746151357889175,
-0.0031569437123835087,
-0.02912253886461258,
0.023407185450196266,
0.051419876515865326,
0.03531038761138916,
0.011811909265816212,
-0.01864015869796276,
0.006131401751190424,
-0.006962109822779894,
-0.06877235323190689,
0.028606876730918884,
-0... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | Next, select “template is ready” in the “Prerequisites” section and “Upload a template” in the “Specify templates” section. From here, you will choose the YAML (or JSON) file containing the MongoDB Atlas deployment that you created in the prior step.
.
The fastest way to get started is to create a MongoDB Atlas account from the AWS Marketplace.
Additionally, you can watch our demo to learn about the other ways to get started with MongoDB Atlas and CloudFormation
Go build with MongoDB Atlas and AWS CloudFormation today! | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.05122458562254906,
-0.02530042827129364,
0.007350148633122444,
-0.010524928569793701,
0.027842823415994644,
0.021863631904125214,
-0.04583825543522835,
0.003944881726056337,
-0.02962489239871502,
-0.018052484840154648,
0.0024154798593372107,
-0.05337638035416603,
0.026192255318164825,
-... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | [1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt6a7a0aace015cbb5/6504a623a8cf8bcfe63e171a/image4.png
[2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt471e37447cf8b1b1/6504a651ea4b5d10aa5135d6/image8.png
[3]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt3545f9cbf7c8f622/6504a67ceb5afe6d504a833b/image13.png | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.03217098489403725,
-0.0043207877315580845,
0.019217468798160553,
-0.01546534150838852,
0.032254695892333984,
0.0203914362937212,
0.0005730482516810298,
0.028891121968626976,
-0.007707154378294945,
-0.034837741404771805,
0.010743200778961182,
-0.09464114904403687,
0.03375709056854248,
0.... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | [4]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt3582d0a3071426e3/6504a69f0433c043b6255189/image12.png
[5]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltb4253f96c019874e/6504a6bace38f40f4df4cddf/image1.png
[6]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt2840c92b6d1ee85d/6504a6d7da83c92f49f9b77e/image7.png | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.033198919147253036,
-0.0022858805023133755,
0.022573476657271385,
-0.02531513385474682,
0.03371371701359749,
0.015225160866975784,
-0.0071481396444141865,
0.02401105873286724,
-0.0070181055925786495,
-0.030547870323061943,
0.01906142570078373,
-0.0800822526216507,
0.038136571645736694,
... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | [7]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltd4a32140ddf600fc/6504a700ea4b5d515f5135db/image5.png
[8]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt49dabfed392fa063/6504a73dbb60f713d4482608/image9.png
[9]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt592e3f129fe1304b/6504a766a8cf8b5ba23e1723/image11.png | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.052878204733133316,
-0.013489857316017151,
0.03641963005065918,
-0.0232711024582386,
0.03356260433793068,
0.022496769204735756,
-0.007606188766658306,
0.030676566064357758,
0.001556290895678103,
-0.043156154453754425,
0.026905808597803116,
-0.091546431183815,
0.04205445572733879,
0.0360... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | [10]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltbff284987187ce16/6504a78bb8c6d6c2d90e6e22/image10.png
[11]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt0ae450069b31dff9/6504a7b99bf261fdd46bddcf/image3.png
[12]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt7f24645eefdab69c/6504a7da9aba461d6e9a55f4/image2.png | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.039220575243234634,
0.0014963907888159156,
0.0313168466091156,
-0.030745921656489372,
0.03752211108803749,
0.007079517934471369,
-0.010885371826589108,
0.035174399614334106,
0.004831007681787014,
-0.02534456178545952,
0.012240174226462841,
-0.08202075213193893,
0.05157741904258728,
0.02... |
devcenter | https://www.mongodb.com/developer/products/atlas/deploy-mongodb-atlas-aws-cloudformation | created | [13]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt7e1c20eba155233a/6504a8088606a80fe5c87f31/image6.png | md | {
"tags": [
"Atlas",
"AWS"
],
"pageDescription": "Learn how to quickly and easily deploy MongoDB Atlas instances with Amazon Web Services (AWS) CloudFormation.",
"contentType": "Tutorial"
} | How to Deploy MongoDB Atlas with AWS CloudFormation | 2024-05-20T17:32:23.500Z | [
-0.03406836837530136,
0.00006771704647690058,
0.02773696929216385,
-0.02781265787780285,
0.0114902313798666,
0.00154711096547544,
-0.008149292320013046,
0.030406218022108078,
-0.007993465289473534,
-0.03727110102772713,
0.025482455268502235,
-0.09371776878833771,
0.021128471940755844,
0.00... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | # How to Integrate MongoDB Into Your Next.js App
> This tutorial uses the Next.js Pages Router instead of the App Router which was introduced in Next.js version 13. The Pages Router is still supported and recommended for production environments.
Are you building your next amazing application with Next.js? Do you wish you could integrate MongoDB into your Next.js app effortlessly? Do you need this done before your coffee has finished brewing? If you answered yes to these three questions, I have some good news for you. We have created a Next.js<>MongoDB integration that will have you up and running in minutes, and you can consider this tutorial your official guide on how to use it. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.05091717094182968,
-0.0035527863074094057,
0.02439594268798828,
-0.05126512795686722,
0.025426870211958885,
-0.02679506316781044,
-0.0391407236456871,
0.01078982837498188,
0.0029375809244811535,
-0.003531744470819831,
0.00004127466309000738,
-0.03999471664428711,
0.024899380281567574,
0... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | In this tutorial, we'll take a look at how we can use the **with-mongodb** example to create a new Next.js application that follows MongoDB best practices for connectivity, connection pool monitoring, and querying. We'll also take a look at how to use MongoDB in our Next.js app with things like serverSideProps and APIs. Finally, we'll take a look at how we can easily deploy and host our application on Vercel, the official hosting platform for Next.js applications. If you already have an existing Next.js app, not to worry. Simply drop the MongoDB utility file into your existing project and you are good to go. We have a lot of exciting stuff to cover, so let's dive right in! | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.06978491693735123,
0.015135692432522774,
0.016253117471933365,
-0.07611209154129028,
0.03712327033281326,
-0.00919279269874096,
-0.021473359316587448,
0.003786151995882392,
-0.0037624710239470005,
-0.030912041664123535,
-0.0008145315223373473,
-0.048215605318546295,
0.022445082664489746,
... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | ## Next.js and MongoDB with one click
Our app is now deployed and running in production. If you weren't following along with the tutorial and just want to quickly start your Next.js application with MongoDB, you could always use the `with-mongodb` starter found on GitHub, but I’ve got an even better one for you.
Visit Vercel and you'll be off to the races in creating and deploying the official Next.js with the MongoDB integration, and all you'll need to provide is your connection string.
## Prerequisites
For this tutorial, you'll need:
- MongoDB Atlas (sign up for free).
- A Vercel account (sign up for free).
- NodeJS 18+.
- npm and npx.
To get the most out of this tutorial, you need to be familiar with React and Next.js. I will cover unique Next.js features with enough details to still be valuable to a newcomer. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.07331588119268417,
-0.007387739606201649,
0.03933708369731903,
-0.0619853138923645,
0.03491160646080971,
0.010563663206994534,
-0.03459610417485237,
-0.0009352266788482666,
-0.0017970841145142913,
-0.04273605719208717,
-0.004332574084401131,
-0.07404487580060959,
0.025871461257338524,
0... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | ## What is Next.js?
If you're not already familiar with it, Next.js is a React-based framework for building modern web applications. The framework adds a lot of powerful features — such as server-side rendering, automatic code splitting, and incremental static regeneration — that make it easy to build, scalable, and production-ready apps.
. You can use a local MongoDB installation if you have one, but if you're just getting started, MongoDB Atlas is a great way to get up and running without having to install or manage your MongoDB instance. MongoDB Atlas has a forever free tier that you can sign up for as well as get the sample data that we'll be using for the rest of this tutorial.
To get our MongoDB URI, in our MongoDB Atlas dashboard: | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.06650304794311523,
-0.010857834480702877,
0.013117867521941662,
-0.0421123281121254,
0.04913495481014252,
0.01354681421071291,
-0.03373359516263008,
0.008091864176094532,
0.01712179370224476,
-0.029484054073691368,
0.00486372783780098,
-0.03683509677648544,
0.0025807477068156004,
0.0444... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | To get our MongoDB URI, in our MongoDB Atlas dashboard:
1. Hit the **Connect** button.
2. Then, click the **Connect to your application** button, and here you'll see a string that contains your **URI** that will look like this:
```
mongodb+srv://:@cluster0..mongodb.net/?retryWrites=true&w=majority
```
If you are new to MongoDB Atlas, you'll need to go to the **Database Access** section and create a username and password, as well as the **Network Access** tab to ensure your IP is allowed to connect to the database. However, if you already have a database user and network access enabled, you'll just need to replace the `` and `` fields with your information.
For the ``, we'll load the MongoDB Atlas sample datasets and use one of those databases.
, and we'll help troubleshoot. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.061701688915491104,
-0.04253983497619629,
0.014697193168103695,
-0.012526524253189564,
0.0203979704529047,
0.00273298192769289,
0.03841505944728851,
0.01597476191818714,
-0.0033922733273357153,
-0.02007523737847805,
0.004304900765419006,
-0.04132925346493721,
0.045536816120147705,
0.034... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | For the ``, we'll load the MongoDB Atlas sample datasets and use one of those databases.
, and we'll help troubleshoot.
## Querying MongoDB with Next.js
Now that we are connected to MongoDB, let's discuss how we can query our MongoDB data and bring it into our Next.js application. Next.js supports multiple ways to get data. We can create API endpoints, get data by running server-side rendered functions for a particular page, and even generate static pages by getting our data at build time. We'll look at all three examples.
## Example 1: Next.js API endpoint with MongoDB
The first example we'll look at is building and exposing an API endpoint in our Next.js application. To create a new API endpoint route, we will first need to create an `api` directory in our `pages` directory, and then every file we create in this `api` directory will be treated as an individual API endpoint. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.05682733282446861,
-0.002558856038376689,
0.026809358969330788,
-0.054368164390325546,
0.03055047243833542,
-0.002027659211307764,
-0.00936425756663084,
-0.0025921454653143883,
-0.013027796521782875,
-0.04335874319076538,
0.007278938312083483,
-0.033978935331106186,
0.0004032631404697895,... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | Let's go ahead and create the `api` directory and a new file in this `directory` called `movies.tsx`. This endpoint will return a list of 20 movies from our MongoDB database. The implementation for this route is as follows:
```
import clientPromise from "../../lib/mongodb";
import { NextApiRequest, NextApiResponse } from 'next';
export default async (req: NextApiRequest, res: NextApiResponse) => {
try {
const client = await clientPromise;
const db = client.db("sample_mflix");
const movies = await db
.collection("movies")
.find({})
.sort({ metacritic: -1 })
.limit(10)
.toArray();
res.json(movies);
} catch (e) {
console.error(e);
}
}
``` | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.08413121849298477,
-0.013491722755134106,
0.03753519058227539,
-0.04501663148403168,
0.03524985536932945,
-0.005136992782354355,
0.010879690758883953,
-0.005656496621668339,
0.027962325140833855,
-0.009257509373128414,
0.031008178368210793,
-0.037337254732847214,
0.01085659209638834,
0.... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | To explain what is going on here, we'll start with the import statement. We are importing our `clientPromise` method from the `lib/mongodb` file. This file contains all the instructions on how to connect to our MongoDB Atlas cluster. Additionally, within this file, we cache the instance of our connection so that subsequent requests do not have to reconnect to the cluster. They can use the existing connection. All of this is handled for you!
Next, our API route handler has the signature of `export default async (req, res)`. If you're familiar with Express.js, this should look very familiar. This is the function that gets run when the `localhost:3000/api/movies` route is called. We capture the request via `req` and return the response via the `res` object. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.04080770164728165,
-0.014187704771757126,
0.007827481254935265,
-0.005622378084808588,
0.030692078173160553,
-0.02683299221098423,
0.0438162125647068,
-0.008875356987118721,
0.006549777928739786,
-0.01643410325050354,
0.03642597794532776,
-0.058663949370384216,
-0.021883724257349968,
0.... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | Our handler function implementation calls the `clientPromise` function to get the instance of our MongoDB database. Next, we run a MongoDB query using the MongoDB Node.js driver to get the top 20 movies out of our **movies** collection based on their **metacritic** rating sorted in descending order.
Finally, we call the `res.json` method and pass in our array of movies. This serves our movies in JSON format to our browser. If we navigate to `localhost:3000/api/movies`, we'll see a result that looks like this: | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.03949460759758949,
-0.005377274937927723,
0.00629689684137702,
-0.02052428387105465,
0.0445094034075737,
-0.00857863761484623,
0.03903236985206604,
-0.0029697122517973185,
0.03043171763420105,
-0.008273706771433353,
0.028260083869099617,
-0.02497355453670025,
0.005518490914255381,
0.034... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | to capture the `id`. So, if a user calls `http://localhost:3000/api/movies/573a1394f29313caabcdfa3e`, the movie that should be returned is Seven Samurai. **Another tip**: The `_id` property for the `sample_mflix` database in MongoDB is stored as an ObjectID, so you'll have to convert the string to an ObjectID. If you get stuck, create a thread on the MongoDB Community forums and we'll solve it together! Next, we'll take a look at how to access our MongoDB data within our Next.js pages.
## Example 2: Next.js pages with MongoDB
In the last section, we saw how we can create an API endpoint and connect to MongoDB with it. In this section, we'll get our data directly into our Next.js pages. We'll do this using the getServerSideProps() method that is available to Next.js pages. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.05308668315410614,
-0.0027448690962046385,
0.006311097647994757,
-0.033480629324913025,
0.023331422358751297,
-0.005645269528031349,
0.03145787492394447,
0.014674024656414986,
0.003098683897405863,
-0.03459465876221657,
-0.01884458027780056,
-0.04600854963064194,
0.045073483139276505,
0... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | The `getServerSideProps()` method forces a Next.js page to load with server-side rendering. What this means is that every time this page is loaded, the `getServerSideProps()` method runs on the back end, gets data, and sends it into the React component via props. The code within `getServerSideProps()` is never sent to the client. This makes it a great place to implement our MongoDB queries.
Let's see how this works in practice. Let's create a new file in the `pages` directory, and we'll call it `movies.tsx`. In this file, we'll add the following code:
```
import clientPromise from "../lib/mongodb";
import { GetServerSideProps } from 'next';
interface Movie {
_id: string;
title: string;
metacritic: number;
plot: string;
}
interface MoviesProps {
movies: Movie];
} | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.06791716814041138,
0.00970955565571785,
0.015756264328956604,
-0.04637715220451355,
0.01597617007791996,
-0.00572946947067976,
0.039456479251384735,
0.03633836656808853,
0.022398153319954872,
-0.017584942281246185,
0.013807207345962524,
-0.013827488757669926,
0.03139973431825638,
0.0390... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | interface MoviesProps {
movies: Movie];
}
const Movies: React.FC = ({ movies }) => {
return (
TOP 20 MOVIES OF ALL TIME
(According to Metacritic)
{movies.map((movie) => (
{MOVIE.TITLE}
{MOVIE.METACRITIC}
{movie.plot}
))}
);
};
export default Movies; | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.08184941858053207,
-0.02953866869211197,
0.008570076897740364,
-0.03569154441356659,
0.04046177864074707,
0.021024612709879875,
0.03928661718964577,
0.026221085339784622,
0.02207108959555626,
-0.014812877401709557,
-0.0057913740165531635,
-0.0599047876894474,
0.03612937405705452,
0.0550... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | export const getServerSideProps: GetServerSideProps = async () => {
try {
const client = await clientPromise;
const db = client.db("sample_mflix");
const movies = await db
.collection("movies")
.find({})
.sort({ metacritic: -1 })
.limit(20)
.toArray();
return {
props: { movies: JSON.parse(JSON.stringify(movies)) },
};
} catch (e) {
console.error(e);
return { props: { movies: [] } };
}
};
```
As you can see from the example above, we are importing the same `clientPromise` utility class, and our MongoDB query is exactly the same within the `getServerSideProps()` method. The only thing we really needed to change in our implementation is how we parse the response. We need to stringify and then manually parse the data, as Next.js is strict. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.0726381167769432,
0.002975661540403962,
-0.012631257064640522,
-0.05644145607948303,
0.036750029772520065,
-0.03653828054666519,
0.03789034113287926,
0.01676994003355503,
0.03038822114467621,
-0.010426053777337074,
0.0019497150788083673,
-0.04342467337846756,
0.020575568079948425,
0.025... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | Our page component called `Movies` gets the props from our `getServerSideProps()` method, and we use that data to render the page showing the top movie title, metacritic rating, and plot. Your result should look something like this:
![Top 20 movies][6]
This is great. We can directly query our MongoDB database and get all the data we need for a particular page. The contents of the `getServerSideProps()` method are never sent to the client, but the one downside to this is that this method runs every time we call the page. Our data is pretty static and unlikely to change all that often. What if we pre-rendered this page and didn't have to call MongoDB on every refresh? We'll take a look at that next! | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.07934286445379257,
0.024927552789449692,
0.008632437326014042,
-0.03727265074849129,
0.02639603801071644,
0.0029331708792597055,
0.022144939750432968,
0.036172036081552505,
0.018635347485542297,
0.0023246079217642546,
0.010047949850559235,
0.008073222823441029,
0.047162171453237534,
0.0... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | ## Example 3: Next.js static generation with MongoDB
For our final example, we'll take a look at how static page generation can work with MongoDB. Let's create a new file in the `pages` directory and call it `top.tsx`. For this page, what we'll want to do is render the top 1,000 movies from our MongoDB database.
Top 1,000 movies? Are you out of your mind? That'll take a while, and the database round trip is not worth it. Well, what if we only called this method once when we built the application so that even if that call takes a few seconds, it'll only ever happen once and our users won't be affected? They'll get the top 1,000 movies delivered as quickly as or even faster than the 20 using `serverSideProps()`. The magic lies in the `getStaticProps()` method, and our implementation looks like this: | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.08200717717409134,
0.019842373207211494,
0.006574586965143681,
-0.048410262912511826,
0.04935380443930626,
0.0016335244290530682,
-0.026443805545568466,
0.003986811731010675,
0.002904495457187295,
-0.023392029106616974,
0.02663506753742695,
-0.013289735652506351,
0.008659806102514267,
0... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | ```
import { ObjectId } from "mongodb";
import clientPromise from "../lib/mongodb";
import { GetStaticProps } from "next";
interface Movie {
_id: ObjectId;
title: string;
metacritic: number;
plot: string;
}
interface TopProps {
movies: Movie[];
}
export default function Top({ movies }: TopProps) {
return (
TOP 1000 MOVIES OF ALL TIME
(According to Metacritic)
{movies.map((movie) => (
{MOVIE.TITLE}
{MOVIE.METACRITIC}
{movie.plot}
))}
);
}
export const getStaticProps: GetStaticProps = async () => {
try {
const client = await clientPromise;
const db = client.db("sample_mflix"); | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.07732196897268295,
-0.0028191395103931427,
0.017954330891370773,
-0.07057406008243561,
0.03374779224395752,
-0.016224265098571777,
0.032442402094602585,
0.01407907996326685,
0.04335147887468338,
-0.0023040513042360544,
-0.0017834517639130354,
-0.047438833862543106,
0.030973918735980988,
... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | const db = client.db("sample_mflix");
const movies = await db
.collection("movies")
.find({})
.sort({ metacritic: -1 })
.limit(1000)
.toArray();
return {
props: { movies: JSON.parse(JSON.stringify(movies)) },
};
} catch (e) {
console.error(e);
return {
props: { movies: [] },
};
}
};
```
At a glance, this looks very similar to the `movies.tsx` file we created earlier. The only significant changes we made were changing our `limit` from `20` to `1000` and our `getServerSideProps()` method to `getStaticProps()`. If we navigate to `localhost:3000/top` in our browser, we'll see a long list of movies.
![Top 1000 movies][7] | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.07689962536096573,
-0.01311954390257597,
0.05014989897608757,
-0.049845971167087555,
0.031692661345005035,
0.0019217567751184106,
0.020809579640626907,
0.013268438167870045,
0.05017213895916939,
-0.013291768729686737,
0.00988257396966219,
-0.010821443051099777,
0.0353815071284771,
0.059... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | ![Top 1000 movies][7]
Look at how tiny that scrollbar is. Loading this page took about 3.79 seconds on my machine, as opposed to the 981-millisecond response time for the `/movies` page. The reason it takes this long is that in development mode, the `getStaticProps()` method is called every single time (just like the `getServerSideProps()` method). But if we switch from development mode to production mode, we'll see the opposite. The `/top` page will be pre-rendered and will load almost immediately, while the `/movies` and `/api/movies` routes will run the server-side code each time. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.10511308908462524,
-0.021257376298308372,
0.02515305019915104,
-0.024123365059494972,
0.032037440687417984,
0.02732013165950775,
0.00008039743261178955,
0.007103505544364452,
0.040098752826452255,
-0.010298719629645348,
0.012645035982131958,
0.001660182373598218,
0.042859453707933426,
0... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | Let's switch to production mode. In your terminal window, stop the current app from running. To run our Next.js app in production mode, we'll first need to build it. Then, we can run the `start` command, which will serve our built application. In your terminal window, run the following commands:
```
npm run build
npm run start
```
When you run the `npm run start` command, your Next.js app is served in production mode. The `getStaticProps()` method will not be run every time you hit the `/top` route as this page will now be served statically. We can even see the pre-rendered static page by navigating to the `.next/server/pages/top.html` file and seeing the 1,000 movies listed in plain HTML. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.04567830637097359,
0.014786011539399624,
0.04421338811516762,
-0.057106759399175644,
0.042399123311042786,
0.03348507732152939,
0.0035972867626696825,
0.0016018872847780585,
-0.00277165905572474,
-0.03651996701955795,
0.02198774740099907,
-0.023785030469298363,
0.014511496759951115,
0.0... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | Next.js can even update this static content without requiring a rebuild with a feature called [Incremental Static Regeneration, but that's outside of the scope of this tutorial. Next, we'll take a look at deploying our application on Vercel.
## Deploying your Next.js app on Vercel
The final step in our tutorial today is deploying our application. We'll deploy our Next.js with MongoDB app to Vercel. I have created a GitHub repo that contains all of the code we have written today. Feel free to clone it, or create your own.
Navigate to Vercel and log in. Once you are on your dashboard, click the **Import Project** button, and then **Import Git Repository**.
, https://nextjs-with-mongodb-mauve.vercel.app/api/movies, and https://nextjs-with-mongodb-mauve.vercel.app/top routes. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.083499014377594,
-0.023502593860030174,
0.05679013207554817,
-0.06440140306949615,
0.036152176558971405,
0.02100345492362976,
-0.07245520502328873,
0.00984513945877552,
-0.01820792257785797,
-0.045378223061561584,
0.024564048275351524,
-0.052754998207092285,
0.02976970002055168,
0.00567... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | ## Putting it all together
In this tutorial, we walked through the official Next.js with MongoDB example. I showed you how to connect your MongoDB database to your Next.js application and run queries in multiple ways. Then, we deployed our application using Vercel.
If you have any questions or feedback, reach out through the MongoDB Community forums and let me know what you build with Next.js and MongoDB. | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.06619331985712051,
0.014232930727303028,
0.02264905348420143,
-0.0738404169678688,
0.03399281948804855,
0.0009515137644484639,
-0.042180582880973816,
-0.000898331927601248,
0.0000301612035400467,
-0.033645447343587875,
-0.020732002332806587,
-0.06568428874015808,
0.03513399511575699,
0.... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | [1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt572f8888407a2777/65de06fac7f05b1b2f8674cc/vercel-homepage.png
[2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt833e93bc334716a5/65de07c677ae451d96b0ec98/server-error.png
[3]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltad2329fe1bb44d8f/65de1b020f1d350dd5ca42a5/database-deployments.png | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.07197485119104385,
-0.04556358978152275,
0.0635908991098404,
-0.044109322130680084,
0.041805122047662735,
0.005983847193419933,
-0.024220671504735947,
0.008180590346455574,
0.00440394040197134,
-0.02306322567164898,
0.04248539358377457,
-0.09223457425832748,
0.03795583173632622,
0.03297... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | [4]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt798b7c3fe361ccbd/65de1b917c85267d37234400/welcome-nextjs.png
[5]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blta204dc4bce246ac6/65de1ff8c7f05b0b4b86759a/json-format.png
[6]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt955fc3246045aa82/65de2049330e0026817f6094/top-20-movies.png | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.09084164351224899,
-0.02250589244067669,
0.03162126615643501,
-0.06294838339090347,
0.06777750700712204,
0.026305779814720154,
-0.01418217271566391,
0.00885816104710102,
-0.006892760284245014,
-0.05282166600227356,
0.019261617213487625,
-0.08013585954904556,
0.014574258588254452,
0.0283... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | [7]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltfb7866c7c87e81ef/65de2098ae62f777124be71d/top-1000-movie.png
[8]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltc89beb7757ffec1e/65de20e0ee3a13755fc8e7fc/importing-project-vercel.png
[9]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt0022681a81165d94/65de21086c65d7d78887b5ff/configuring-project.png | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.05935702472925186,
-0.03701744228601456,
0.022441182285547256,
-0.08058218657970428,
0.04208818078041077,
0.009208179078996181,
-0.020943015813827515,
0.0019184109987691045,
-0.02465016394853592,
-0.013017919845879078,
0.028959419578313828,
-0.10566168278455734,
0.057245008647441864,
0.... |
devcenter | https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb | created | [10]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt7b00b1cfe190a7d4/65de212ac5985207f8f6b232/congratulations.png | md | {
"tags": [
"JavaScript",
"Next.js"
],
"pageDescription": "Learn how to easily integrate MongoDB into your Next.js application with the official MongoDB package.",
"contentType": "Tutorial"
} | How to Integrate MongoDB Into Your Next.js App | 2024-05-20T17:32:23.500Z | [
-0.05522237718105316,
0.027641287073493004,
0.028337405994534492,
-0.030491236597299576,
0.0032045708503574133,
0.031036969274282455,
0.024529987946152687,
0.038770467042922974,
0.030578918755054474,
0.00014155123790260404,
0.005046718288213015,
-0.07623045891523361,
-0.006517007946968079,
... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | # How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI
Building applications with Go provides many advantages. The language is fast, simple, and lightweight while supporting powerful features like concurrency, strong typing, and a robust standard library. In this tutorial, we’ll use the popular Gin web framework along with MongoDB to build a Go-based web application.
Gin is a minimalist web framework for Golang that provides an easy way to build web servers and APIs. It is fast, lightweight, and modular, making it ideal for building microservices and APIs, but can be easily extended to build full-blown applications.
We'll use Gin to build a web application with three endpoints that connect to a MongoDB database. MongoDB is a popular document-oriented NoSQL database that stores data in JSON-like documents. MongoDB is a great fit for building modern applications. | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.06787771731615067,
-0.012960485182702541,
0.0006823365692980587,
-0.031336840242147446,
0.0005002072430215776,
-0.0019981965888291597,
-0.011269290000200272,
0.0245248693972826,
-0.025746358558535576,
0.00892161950469017,
-0.002255581319332123,
-0.02585158310830593,
0.05319559946656227,
... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | Rather than building the entire application by hand, we’ll leverage a coding AI assistant by Sourcegraph called Cody to help us build our Go application. Cody is the only AI assistant that knows your entire codebase and can help you write, debug, test, and document your code. We’ll use many of these features as we build our application today.
## Prerequisites
Before you begin, you’ll need:
- Go installed on your development machine. Download it on their website.
- A MongoDB Atlas account. Sign up for free.
- Basic familiarity with Go and MongoDB syntax.
- Sourcegraph Cody installed in your favorite IDE. (For this tutorial, we'll be using VS Code). Get it for free.
Once you meet the prerequisites, you’re ready to build. Let’s go.
## Getting started | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.04911436140537262,
-0.02002384327352047,
0.011819763109087944,
-0.026090355589985847,
0.0070401933044195175,
-0.002453114604577422,
0.01636004075407982,
0.03129266947507858,
-0.049594223499298096,
0.006113497540354729,
-0.007689142599701881,
-0.0656534805893898,
0.056570589542388916,
0.... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | Once you meet the prerequisites, you’re ready to build. Let’s go.
## Getting started
We'll start by creating a new Go project for our application. For this example, we’ll name the project **mflix**, so let’s go ahead and create the project directory and navigate into it:
```bash
mkdir mflix
cd mflix
```
Next, initialize a new Go module, which will manage dependencies for our project:
```bash
go mod init mflix
```
Now that we have our Go module created, let’s install the dependencies for our project. We’ll keep it really simple and just install the `gin` and `mongodb` libraries.
```bash
go get github.com/gin-gonic/gin
go get go.mongodb.org/mongo-driver/mongo
```
With our dependencies fetched and installed, we’re ready to start building our application.
## Gin application setup with Cody | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.0393575094640255,
-0.01464158296585083,
0.035994503647089005,
-0.05541827902197838,
-0.006708794739097357,
-0.00030420927214436233,
-0.020268550142645836,
0.024914070963859558,
-0.04246092215180397,
-0.014285317622125149,
0.010057779960334301,
-0.0577499121427536,
0.06342416256666183,
0... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | With our dependencies fetched and installed, we’re ready to start building our application.
## Gin application setup with Cody
To start building our application, let’s go ahead and create our entry point into the app by creating a **main.go** file. Next, while we can set up our application manually, we’ll instead leverage Cody to build out our starting point. In the Cody chat window, we can ask Cody to create a basic Go Gin application.
guide. The database that we will work with is called `sample_mflix` and the collection in that database we’ll use is called `movies`. This dataset contains a list of movies with various information like the plot, genre, year of release, and much more.
on the movies collection. Aggregation operations process multiple documents and return computed results. So with this endpoint, the end user could pass in any valid MongoDB aggregation pipeline to run various analyses on the `movies` collection. | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.055039599537849426,
-0.022808924317359924,
0.012010747566819191,
-0.05039064213633537,
-0.00813840702176094,
-0.0073469108901917934,
0.007991711609065533,
0.008952494710683823,
-0.04051196575164795,
-0.006907064933329821,
0.001612439751625061,
-0.04975254461169243,
0.07331635802984238,
... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | Note that aggregations are very powerful and in a production environment, you probably wouldn’t want to enable this level of access through HTTP request payloads. But for the sake of the tutorial, we opted to keep it in. As a homework assignment for further learning, try using Cody to limit the number of stages or the types of operations that the end user can perform on this endpoint. | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.03626853972673416,
-0.05535136163234711,
0.004521859344094992,
-0.032165057957172394,
-0.01100823562592268,
0.011267037130892277,
0.026952212676405907,
0.005513760726898909,
0.004569754935801029,
-0.013932806439697742,
0.012227154336869717,
-0.047977834939956665,
0.0666903704404831,
0.0... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | ```go
// POST /movies/aggregations - Run aggregations on movies
func aggregateMovies(c *gin.Context) {
// Get aggregation pipeline from request body
var pipeline interface{}
if err := c.ShouldBindJSON(&pipeline); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Run aggregations
cursor, err := mongoClient.Database("sample_mflix").Collection("movies").Aggregate(context.TODO(), pipeline)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Map results
var result ]bson.M
if err = cursor.All(context.TODO(), &result); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Return result
c.JSON(http.StatusOK, result)
}
``` | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.07706353068351746,
-0.04038127139210701,
0.026832031086087227,
-0.015367158688604832,
0.02524922974407673,
-0.005921077914535999,
0.008182321675121784,
-0.013385878875851631,
-0.020976919680833817,
-0.01635492965579033,
0.02561192587018013,
-0.11304902285337448,
0.035426292568445206,
0.... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | // Return result
c.JSON(http.StatusOK, result)
}
```
Now that we have our endpoints implemented, let’s add them to our router so that we can call them. Here again, we can use another feature of Cody, called autocomplete, to intelligently give us statement completions so that we don’t have to write all the code ourselves.
![Cody AI Autocomplete with Go][6]
Our `main` function should now look like:
```go
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello World",
})
})
r.GET("/movies", getMovies)
r.GET("/movies/:id", getMovieByID)
r.POST("/movies/aggregations", aggregateMovies)
r.Run()
}
``` | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.05938602238893509,
-0.014004160650074482,
0.03543040528893471,
-0.002516123466193676,
0.0021006392780691385,
0.00879143737256527,
0.032836344093084335,
0.06359874457120895,
-0.01115456037223339,
-0.027797410264611244,
-0.021565353497862816,
-0.030437715351581573,
0.0487184040248394,
0.0... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | r.Run()
}
```
Now that we have our routes set up, let’s test our application to make sure everything is working well. Restart the server and navigate to **localhost:8080/movies**. If all goes well, you should see a large list of movies returned in JSON format in your browser window. If you do not see this, check your IDE console to see what errors are shown.
![Sample Output for the Movies Endpoint][7]
Let’s test the second endpoint. Pick any `id` from the movies collection and navigate to **localhost:8080/movies/{id}** — so for example, **localhost:8080/movies/573a1390f29313caabcd42e8**. If everything goes well, you should see that single movie listed. But if you’ve been following this tutorial, you actually won’t see the movie.
![String to Object ID Results Error][8] | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.06483202427625656,
-0.025853043422102928,
0.03659021481871605,
0.012926132418215275,
0.029615670442581177,
0.008374655619263649,
0.0007005480001680553,
0.020831769332289696,
0.010043771006166935,
-0.017459869384765625,
0.043202485889196396,
-0.023029286414384842,
0.016834169626235962,
0... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | ![String to Object ID Results Error][8]
The issue is that in our `getMovie` function implementation, we are accepting the `id` value as a `string`, while the data type in our MongoDB database is an `ObjectID`. So when we run the `FindOne` method and try to match the string value of `id` to the `ObjectID` value, we don’t get a match.
Let’s ask Cody to help us fix this by converting the string input we get to an `ObjectID`.
![Cody AI MongoDB String to ObjectID][9]
Our updated `getMovieByID` function is as follows:
```go
func getMovieByID(c *gin.Context) {
// Get movie ID from URL
idStr := c.Param("id") | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.06964364647865295,
-0.009724597446620464,
0.0018036237452179193,
0.0012720117811113596,
0.009976607747375965,
-0.04142439365386963,
0.03506843000650406,
0.01502987090498209,
0.0007704202434979379,
-0.0017147327307611704,
-0.007296479307115078,
-0.07055879384279251,
0.07563955336809158,
... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | ```go
func getMovieByID(c *gin.Context) {
// Get movie ID from URL
idStr := c.Param("id")
// Convert id string to ObjectId
id, err := primitive.ObjectIDFromHex(idStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Find movie by ObjectId
var movie bson.M
err = mongoClient.Database("sample_mflix").Collection("movies").FindOne(context.TODO(), bson.D{{"_id", id}}).Decode(&movie)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Return movie
c.JSON(http.StatusOK, movie)
}
```
Depending on your IDE, you may need to add the `primitive` dependency in your import statement. The final import statement looks like:
```go
import (
"context"
"log"
"net/http" | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.0685332864522934,
-0.0014796762261539698,
0.03180394321680069,
-0.025883419439196587,
0.02782430127263069,
-0.01769174449145794,
0.05349667742848396,
0.018662355840206146,
-0.038612257689237595,
0.0008505504811182618,
0.00007356749847531319,
-0.07971331477165222,
0.06278591603040695,
0.... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | ```go
import (
"context"
"log"
"net/http"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
```
If we examine the new code that Cody provided, we can see that we are now getting the value from our `id` parameter and storing it into a variable named `idStr`. We then use the primitive package to try and convert the string to an `ObjectID`. If the `idStr` is a valid string that can be converted to an `ObjectID`, then we are good to go and we use the new `id` variable when doing our `FindOne` operation. If not, then we get an error message back. | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.023004325106739998,
-0.015790536999702454,
0.016936462372541428,
-0.01364209782332182,
-0.0016608020523563027,
-0.019356945529580116,
0.05201926454901695,
0.04129093140363693,
-0.022341130301356316,
-0.02693437598645687,
0.009278630837798119,
-0.054840851575136185,
0.03636576235294342,
... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | Restart your server and now try to get a single movie result by navigating to **localhost:8080/movies/{id}**.
![Single Movie Response Endpoint][10]
For our final endpoint, we are allowing the end user to provide an aggregation pipeline that we will execute on the `mflix` collection. The user can provide any aggregation they want. To test this endpoint, we’ll make a POST request to **localhost:8080/movies/aggregations**. In the body of the request, we’ll include our aggregation pipeline.
![Postman Aggregation Endpoint in MongoDB][11] | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.05939396843314171,
-0.022953838109970093,
0.028358299285173416,
-0.015371912159025669,
0.0005927639431320131,
-0.003748072776943445,
0.00951032992452383,
0.008553973399102688,
-0.02210836112499237,
-0.034420326352119446,
0.03477118909358978,
-0.07884728908538818,
0.032459378242492676,
0... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | ![Postman Aggregation Endpoint in MongoDB][11]
Let’s run an aggregation to return a count of comedy movies, grouped by year, in descending order. Again, remember aggregations are very powerful and can be abused. You normally would not want to give direct access to the end user to write and run their own aggregations ad hoc within an HTTP request, unless it was for something like an internal tool. Our aggregation pipeline will look like the following:
```json
[
{"$match": {"genres": "Comedy"}},
{"$group": {
"_id": "$year",
"count": {"$sum": 1}
}},
{"$sort": {"count": -1}}
]
```
Running this aggregation, we’ll get a result set that looks like this: | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.07401272654533386,
-0.0269711185246706,
0.01877683959901333,
-0.019535332918167114,
0.03007514216005802,
-0.021243993192911148,
0.026631206274032593,
-0.004758930765092373,
0.013068437576293945,
-0.01688944548368454,
0.03419562056660652,
-0.04383700713515282,
0.03483673185110092,
0.0395... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | Running this aggregation, we’ll get a result set that looks like this:
```json
[
{
"_id": 2014,
"count": 287
},
{
"_id": 2013,
"count": 286
},
{
"_id": 2009,
"count": 268
},
{
"_id": 2011,
"count": 263
},
{
"_id": 2006,
"count": 260
},
...
]
```
It seems 2014 was a big year for comedy. If you are not familiar with how aggregations work, you can check out the following resources:
- [Introduction to the MongoDB Aggregation Framework
- MongoDB Aggregation Pipeline Queries vs SQL Queries
- A Better MongoDB Aggregation Experience via Compass | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.06820350140333176,
-0.029377540573477745,
0.023366276174783707,
-0.018552958965301514,
0.02511957287788391,
-0.012584185227751732,
0.04258553683757782,
0.023017894476652145,
0.031415607780218124,
-0.00668705627322197,
0.023607298731803894,
-0.034718867391347885,
0.04244041070342064,
0.0... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | - [Introduction to the MongoDB Aggregation Framework
- MongoDB Aggregation Pipeline Queries vs SQL Queries
- A Better MongoDB Aggregation Experience via Compass
Additionally, you can ask Cody for a specific explanation about how our `aggregateMovies` function works to help you further understand how the code is implemented using the Cody `/explain` command.
.
And if you have any questions or comments, let’s continue the conversation in our developer forums!
The entire code for our application is above, so there is no GitHub repo for this simple application. Happy coding. | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.05043232440948486,
-0.040659449994564056,
-0.0008779990021139383,
-0.01649775356054306,
0.028525717556476593,
-0.02412003092467785,
0.011591386049985886,
0.015299403108656406,
-0.015202571637928486,
-0.011851189658045769,
-0.009630112908780575,
-0.06817132234573364,
0.05715791881084442,
... |
devcenter | https://www.mongodb.com/developer/products/mongodb/build-go-web-application-gin-mongodb-help-ai | created | [1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt123181346af4c7e6/65148770b25810649e804636/eVB87PA.gif
[2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt3df7c0149a4824ac/6514820f4f2fa85e60699bf8/image4.png
[3]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt6a72c368f716c7c2/65148238a5f15d7388fc754a/image2.png | md | {
"tags": [
"MongoDB",
"Go"
],
"pageDescription": "Learn how to build a web application with the Gin framework for Go and MongoDB using the help of Cody AI from Sourcegraph.",
"contentType": "Tutorial"
} | How to Build a Go Web Application with Gin, MongoDB, and with the Help of AI | 2024-05-20T17:32:23.500Z | [
-0.03157740458846092,
-0.013073869980871677,
0.028578205034136772,
-0.010271021164953709,
0.03574735298752785,
0.03192337602376938,
-0.0028953172732144594,
0.03383856266736984,
-0.0016590297454968095,
-0.0314883254468441,
0.014228236861526966,
-0.09247218072414398,
0.0219525545835495,
0.01... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.