- Stitch >
- MongoDB Atlas >
- Work With MongoDB
Add Data to MongoDB¶
On this page
Overview¶
The code snippets on this page demonstrate how to insert one or more documents into a MongoDB collection. Insert operations take the documents to add to MongoDB as an argument and return documents that describe the results of the operation.
Data Model¶
The examples on this page use a collection named store.items
that
models various items available for purchase in an online store. Each
item has a name
, an inventory quantity
, and an array of customer
reviews
.
Snippet Setup¶
- Functions
- JavaScript SDK
- Android SDK
- iOS SDK
To use a code snippet in a function, you must first instantiate a MongoDB collection handle:
To use a code snippet in a JavaScript project, you must first do the following:
Import Stitch Dependencies¶
– or –
Instantiate a MongoDB Remote Collection Handle¶
To use a code snippet in an Android project, you must first do the following:
Set Up Your Project¶
Follow the steps in the Set up a MongoDB Mobile Project guide.
Note
For more details on setting up your Android app to use Stitch, refer to Build a Mobile App with Sync or Build a Local-Only Mobile App.
Import Stitch Dependencies¶
For CRUD operations on a remote MongoDB collection, you will use one
or more of the following import
statements:
To Sync documents between a remote and a local MongoDB instance, you will also need to import the following packages:
Important
If you use Sync, be sure to add .sync()
before every remote
database call in the examples below, as in the following:
To perform CRUD operations only on the local (on-device) database, import the following packages:
Instantiate a MongoDB Collection Handle¶
To use a code snippet in an iOS project, you must first do the following:
Set Up Your Project¶
Follow the steps in the Set up a MongoDB Mobile Project guide.
Import Stitch Dependencies¶
Initialize the MongoDB Stitch iOS SDK¶
Instantiate a MongoDB Collection Handle¶
Methods¶
Insert a Single Document¶
You can insert a single document using the
collection.insertOne()
action.
The following snippet inserts a single item document into the items
collection:
- Functions
- JavaScript SDK
- Android SDK
- iOS SDK
Insert One or More Documents¶
You can insert multiple documents at the same time using the
collection.insertMany()
action.
The following snippet inserts multiple item documents into the items
collection:
- Functions
- JavaScript SDK
- Android SDK
- iOS SDK