➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples or select MongoDB Compass.
This page provides examples of insert operations in MongoDB.
You can insert documents in MongoDB by using the following methods:
Your programming language's driver.
The MongoDB Atlas UI. To learn more, see Insert Documents in the MongoDB Atlas UI.
If the collection does not currently exist, insert operations will create the collection.
To insert a document in the MongoDB Atlas UI, complete the following steps. To learn more about working with documents in the MongoDB Atlas UI, see Create, View, Update, and Delete Documents.
Warning Navigation Improvements In ProgressWe're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview Atlas documentation.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
For the cluster to which you want to add documents, click Browse Collections.
In the left navigation pane, select the database.
In the left navigation pane, select the collection.
Click Insert Document.
Click the {} icon, which opens the JSON view.
Paste the document array into the text entry field. For example, the following entry creates four documents, each of which contain three fields:
[ { "prodId": 100, "price": 20, "quantity": 125 }, { "prodId": 101, "price": 10, "quantity": 234 }, { "prodId": 102, "price": 15, "quantity": 432 }, { "prodId": 103, "price": 17, "quantity": 320 }]
MongoDB Atlas adds the documents to the collection.
db.collection.insertOne()
inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, MongoDB adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
To insert a single document using MongoDB Compass:
Navigate to the collection you wish to insert the document into:
In the left-hand MongoDB Compass navigation pane, click the database to which your target collection belongs.
From the database view, click the target collection name.
Click the Add Data button, then click Insert document:
Paste in your document. For example, you can paste the following code into Compass to insert a canvas
document into the inventory
collection:
{ "item": "canvas", "qty": 100, "tags": ["cotton"], "size": { "h": 28, "w": 35.5, "uom": "cm" }}
Click Insert.
The following example inserts a new document into the test.inventory collection:
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the C driver adds the _id
field with an ObjectId value to the new document. For more information, see Insert Behavior.
IMongoCollection.InsertOne() inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the C# driver adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
Collection.InsertOne inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the driver adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
MongoCollection.insertOne inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the driver adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
Collection.insertOne() inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the Node.js driver adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
MongoDB\\Collection::insertOne()
inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the PHP driver adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
Mongo::Collection#insert_one() inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the Ruby driver adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
collection.insertOne() inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. If the document does not specify an _id
field, the Scala driver adds the _id
field with an ObjectId value to the new document. See Insert Behavior.
db.inventory.insertOne( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } })
mongoc_collection_t *collection;bson_t *doc;bool r;bson_error_t error;collection = mongoc_database_get_collection (db, "inventory");doc = BCON_NEW ( "item", BCON_UTF8 ("canvas"), "qty", BCON_INT64 (100), "tags", "[", BCON_UTF8 ("cotton"), "]", "size", "{", "h", BCON_DOUBLE (28), "w", BCON_DOUBLE (35.5), "uom", BCON_UTF8 ("cm"), "}");r = mongoc_collection_insert_one (collection, doc, NULL, NULL, &error);bson_destroy (doc);if (!r) { MONGOC_ERROR ("%s\n", error.message); goto done;}
var document = new BsonDocument{ { "item", "canvas" }, { "qty", 100 }, { "tags", new BsonArray { "cotton" } }, { "size", new BsonDocument { { "h", 28 }, { "w", 35.5 }, { "uom", "cm" } } }};collection.InsertOne(document);
result, err := coll.InsertOne( context.TODO(), bson.D{ {"item", "canvas"}, {"qty", 100}, {"tags", bson.A{"cotton"}}, {"size", bson.D{ {"h", 28}, {"w", 35.5}, {"uom", "cm"}, }}, })
Document canvas = new Document("item", "canvas") .append("qty", 100) .append("tags", singletonList("cotton"));Document size = new Document("h", 28) .append("w", 35.5) .append("uom", "cm");canvas.put("size", size);Publisher<Success> insertOnePublisher = collection.insertOne(canvas);
Document canvas = new Document("item", "canvas") .append("qty", 100) .append("tags", singletonList("cotton"));Document size = new Document("h", 28) .append("w", 35.5) .append("uom", "cm");canvas.put("size", size);collection.insertOne(canvas);
result = collection.insertOne(Document("item", "canvas") .append("qty", 100) .append("tags", listOf("cotton")) .append("size", Document("h", 28) .append("w", 35.5) .append("uom", "cm") )
await db.inventory.insert_one( { "item": "canvas", "qty": 100, "tags": ["cotton"], "size": {"h": 28, "w": 35.5, "uom": "cm"}, })
await db.collection('inventory').insertOne({ item: 'canvas', qty: 100, tags: ['cotton'], size: { h: 28, w: 35.5, uom: 'cm' }});
$insertOneResult = $db->inventory->insertOne([ 'item' => 'canvas', 'qty' => 100, 'tags' => ['cotton'], 'size' => ['h' => 28, 'w' => 35.5, 'uom' => 'cm'],]);
db.inventory.insert_one( { "item": "canvas", "qty": 100, "tags": ["cotton"], "size": {"h": 28, "w": 35.5, "uom": "cm"}, })
client[:inventory].insert_one({ item: 'canvas', qty: 100, tags: [ 'cotton' ], size: { h: 28, w: 35.5, uom: 'cm' } })
collection.insertOne( Document("item" -> "canvas", "qty" -> 100, "tags" -> Seq("cotton"), "size" -> Document("h" -> 28, "w" -> 35.5, "uom" -> "cm"))).execute()
Note
MongoDB Compass generates the _id
field and its value automatically. The generated ObjectId consists of a unique randomly generated hexadecimal value.
You can change this value prior to inserting your document so long as it remains unique and is a valid ObjectId
. For more information on the _id
field, see _id Field.
To retrieve the document that you just inserted, query the collection by specifying a filter in the MongoDB Compass query bar and clicking Find to execute the query.
The following filter specifies that MongoDB Compass only return documents where the item
field is equal to canvas
. For more information on the MongoDB Compass Query Bar, see Query Bar.
insertOne() returns a promise that provides a result
. The result.insertedId
promise contains the _id
of the newly inserted document.
To retrieve the document that you just inserted, query the collection:
db.inventory.find( { item: "canvas" } )
mongoc_collection_t *collection;bson_t *filter;mongoc_cursor_t *cursor;collection = mongoc_database_get_collection (db, "inventory");filter = BCON_NEW ("item", BCON_UTF8 ("canvas"));cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var filter = Builders<BsonDocument>.Filter.Eq("item", "canvas");var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{{"item", "canvas"}},)
FindPublisher<Document> findPublisher = collection.find(eq("item", "canvas"));
FindIterable<Document> findIterable = collection.find(eq("item", "canvas"));
val flowInsertOne = collection .find(eq("item", "canvas")) .firstOrNull()
cursor = db.inventory.find({"item": "canvas"})
const cursor = db.collection('inventory').find({ item: 'canvas' });
$cursor = $db->inventory->find(['item' => 'canvas']);
cursor = db.inventory.find({"item": "canvas"})
client[:inventory].find(item: 'canvas')
val observable = collection.find(equal("item", "canvas"))
db.collection.insertMany()
can insert multiple documents into a collection. Pass an array of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, MongoDB adds the _id
field with an ObjectId value to each document. See Insert Behavior.
For instructions on inserting documents using MongoDB Compass, see Insert Documents. You can paste the following documents into the Insert Document dialog in Compass to insert multiple item
documents into the inventory
collection:
mongoc_bulk_operation_insert_with_opts inserts multiple documents into a collection. You must pass an iterable of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the C driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
IMongoCollection.InsertMany() can insert multiple documents into a collection. Pass an enumerable collection of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
Collection.InsertMany can insert multiple documents into a collection.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
com.mongodb.reactivestreams.client.MongoCollection.html.insertMany inserts the following documents with the Java Reactive Streams Driver :
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
com.mongodb.client.MongoCollection.insertMany can insert multiple documents into a collection. Pass a list of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
MongoCollection.insertMany inserts multiple documents into a collection. Pass a list of documents as a parameter to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the driver adds an ObjectId value to each document. See Insert Behavior.
Collection.insertMany() can insert multiple documents into a collection. Pass an array of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the Node.js driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
MongoDB\\Collection::insertMany()
can insert multiple documents into a collection. Pass an array of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the PHP driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
pymongo.collection.Collection.insert_many
can insert multiple documents into a collection. Pass an iterable of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the PyMongo driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
Mongo::Collection#insert_many() can insert multiple documents into a collection. Pass an array of documents to the method.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the Ruby driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
collection.insertMany() can insert multiple documents into a collection.
The following example inserts three new documents into the inventory
collection. If the documents do not specify an _id
field, the Scala driver adds the _id
field with an ObjectId value to each document. See Insert Behavior.
db.inventory.insertMany([ { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }, { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }])
[ { "item": "canvas", "qty": 100, "size": { "h": 28, "w": 35.5, "uom": "cm" }, "status": "A" }, { "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" }, { "item": "mat", "qty": 85, "size": { "h": 27.9, "w": 35.5, "uom": "cm" }, "status": "A" }, { "item": "mousepad", "qty": 25, "size": { "h": 19, "w": 22.85, "uom": "cm" }, "status": "P" }, { "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "P" }, { "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" }, { "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" }, { "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }, { "item": "sketchbook", "qty": 80, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" }, { "item": "sketch pad", "qty": 95, "size": { "h": 22.85, "w": 30.5, "uom": "cm" }, "status": "A" }]
mongoc_collection_t *collection;mongoc_bulk_operation_t *bulk;bson_t *doc;bool r;bson_error_t error;bson_t reply;collection = mongoc_database_get_collection (db, "inventory");bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL);doc = BCON_NEW ( "item", BCON_UTF8 ("journal"), "qty", BCON_INT64 (25), "tags", "[", BCON_UTF8 ("blank"), BCON_UTF8 ("red"), "]", "size", "{", "h", BCON_DOUBLE (14), "w", BCON_DOUBLE (21), "uom", BCON_UTF8 ("cm"), "}");r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);bson_destroy (doc);if (!r) { MONGOC_ERROR ("%s\n", error.message); goto done;}doc = BCON_NEW ( "item", BCON_UTF8 ("mat"), "qty", BCON_INT64 (85), "tags", "[", BCON_UTF8 ("gray"), "]", "size", "{", "h", BCON_DOUBLE (27.9), "w", BCON_DOUBLE (35.5), "uom", BCON_UTF8 ("cm"), "}");r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);bson_destroy (doc);if (!r) { MONGOC_ERROR ("%s\n", error.message); goto done;}doc = BCON_NEW ( "item", BCON_UTF8 ("mousepad"), "qty", BCON_INT64 (25), "tags", "[", BCON_UTF8 ("gel"), BCON_UTF8 ("blue"), "]", "size", "{", "h", BCON_DOUBLE (19), "w", BCON_DOUBLE (22.85), "uom", BCON_UTF8 ("cm"), "}");r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);bson_destroy (doc);if (!r) { MONGOC_ERROR ("%s\n", error.message); goto done;}r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error);if (!r) { MONGOC_ERROR ("%s\n", error.message);}
var documents = new BsonDocument[]{ new BsonDocument { { "item", "journal" }, { "qty", 25 }, { "tags", new BsonArray { "blank", "red" } }, { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm"} } } }, new BsonDocument { { "item", "mat" }, { "qty", 85 }, { "tags", new BsonArray { "gray" } }, { "size", new BsonDocument { { "h", 27.9 }, { "w", 35.5 }, { "uom", "cm"} } } }, new BsonDocument { { "item", "mousepad" }, { "qty", 25 }, { "tags", new BsonArray { "gel", "blue" } }, { "size", new BsonDocument { { "h", 19 }, { "w", 22.85 }, { "uom", "cm"} } } },};collection.InsertMany(documents);
result, err := coll.InsertMany( context.TODO(), []any{ bson.D{ {"item", "journal"}, {"qty", int32(25)}, {"tags", bson.A{"blank", "red"}}, {"size", bson.D{ {"h", 14}, {"w", 21}, {"uom", "cm"}, }}, }, bson.D{ {"item", "mat"}, {"qty", int32(25)}, {"tags", bson.A{"gray"}}, {"size", bson.D{ {"h", 27.9}, {"w", 35.5}, {"uom", "cm"}, }}, }, bson.D{ {"item", "mousepad"}, {"qty", 25}, {"tags", bson.A{"gel", "blue"}}, {"size", bson.D{ {"h", 19}, {"w", 22.85}, {"uom", "cm"}, }}, }, })
Document journal = new Document("item", "journal") .append("qty", 25) .append("tags", asList("blank", "red"));Document journalSize = new Document("h", 14) .append("w", 21) .append("uom", "cm");journal.put("size", journalSize);Document mat = new Document("item", "mat") .append("qty", 85) .append("tags", singletonList("gray"));Document matSize = new Document("h", 27.9) .append("w", 35.5) .append("uom", "cm");mat.put("size", matSize);Document mousePad = new Document("item", "mousePad") .append("qty", 25) .append("tags", asList("gel", "blue"));Document mousePadSize = new Document("h", 19) .append("w", 22.85) .append("uom", "cm");mousePad.put("size", mousePadSize);Publisher<Success> insertManyPublisher = collection.insertMany(asList(journal, mat, mousePad));
Document journal = new Document("item", "journal") .append("qty", 25) .append("tags", asList("blank", "red"));Document journalSize = new Document("h", 14) .append("w", 21) .append("uom", "cm");journal.put("size", journalSize);Document mat = new Document("item", "mat") .append("qty", 85) .append("tags", singletonList("gray"));Document matSize = new Document("h", 27.9) .append("w", 35.5) .append("uom", "cm");mat.put("size", matSize);Document mousePad = new Document("item", "mousePad") .append("qty", 25) .append("tags", asList("gel", "blue"));Document mousePadSize = new Document("h", 19) .append("w", 22.85) .append("uom", "cm");mousePad.put("size", mousePadSize);collection.insertMany(asList(journal, mat, mousePad));
results = collection.insertMany(listOf( Document("item", "journal") .append("qty", 25) .append("tags", listOf("blank", "red")) .append("size", Document("h", 14) .append("w", 21) .append("uom", "cm") ), Document("item", "mat") .append("qty", 25) .append("tags", listOf("gray")) .append("size", Document("h", 27.9) .append("w", 35.5) .append("uom", "cm") ), Document("item", "mousepad") .append("qty", 25) .append("tags", listOf("gel", "blue")) .append("size", Document("h", 19) .append("w", 22.85) .append("uom", "cm") ))
await db.inventory.insert_many( [ { "item": "journal", "qty": 25, "tags": ["blank", "red"], "size": {"h": 14, "w": 21, "uom": "cm"}, }, { "item": "mat", "qty": 85, "tags": ["gray"], "size": {"h": 27.9, "w": 35.5, "uom": "cm"}, }, { "item": "mousepad", "qty": 25, "tags": ["gel", "blue"], "size": {"h": 19, "w": 22.85, "uom": "cm"}, }, ])
await db.collection('inventory').insertMany([ { item: 'journal', qty: 25, tags: ['blank', 'red'], size: { h: 14, w: 21, uom: 'cm' } }, { item: 'mat', qty: 85, tags: ['gray'], size: { h: 27.9, w: 35.5, uom: 'cm' } }, { item: 'mousepad', qty: 25, tags: ['gel', 'blue'], size: { h: 19, w: 22.85, uom: 'cm' } }]);
$insertManyResult = $db->inventory->insertMany([ [ 'item' => 'journal', 'qty' => 25, 'tags' => ['blank', 'red'], 'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'], ], [ 'item' => 'mat', 'qty' => 85, 'tags' => ['gray'], 'size' => ['h' => 27.9, 'w' => 35.5, 'uom' => 'cm'], ], [ 'item' => 'mousepad', 'qty' => 25, 'tags' => ['gel', 'blue'], 'size' => ['h' => 19, 'w' => 22.85, 'uom' => 'cm'], ],]);
db.inventory.insert_many( [ { "item": "journal", "qty": 25, "tags": ["blank", "red"], "size": {"h": 14, "w": 21, "uom": "cm"}, }, { "item": "mat", "qty": 85, "tags": ["gray"], "size": {"h": 27.9, "w": 35.5, "uom": "cm"}, }, { "item": "mousepad", "qty": 25, "tags": ["gel", "blue"], "size": {"h": 19, "w": 22.85, "uom": "cm"}, }, ])
client[:inventory].insert_many([{ item: 'journal', qty: 25, tags: ['blank', 'red'], size: { h: 14, w: 21, uom: 'cm' } }, { item: 'mat', qty: 85, tags: ['gray'], size: { h: 27.9, w: 35.5, uom: 'cm' } }, { item: 'mousepad', qty: 25, tags: ['gel', 'blue'], size: { h: 19, w: 22.85, uom: 'cm' } } ])
collection.insertMany(Seq( Document("item" -> "journal", "qty" -> 25, "tags" -> Seq("blank", "red"), "size" -> Document("h" -> 14, "w" -> 21, "uom" -> "cm")), Document("item" -> "mat", "qty" -> 85, "tags" -> Seq("gray"), "size" -> Document("h" -> 27.9, "w" -> 35.5, "uom" -> "cm")), Document("item" -> "mousepad", "qty" -> 25, "tags" -> Seq("gel", "blue"), "size" -> Document("h" -> 19, "w" -> 22.85, "uom" -> "cm")))).execute()
To view the newly inserted documents, specify a filter of {}
in the MongoDB Compass query bar and click Find to view your documents.
insertMany() returns a promise that provides a result
. The result.insertedIds
field contains an array with the _id
of each newly inserted document.
To retrieve the inserted documents, query the collection:
Upon successful insert, the insertMany() method returns an Observable with a type parameter indicating when the operation has completed or with either a com.mongodb.DuplicateKeyException
or com.mongodb.MongoException
.
To retrieve the inserted documents, query the collection:
var filter = Builders<BsonDocument>.Filter.Empty;var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{},)
FindPublisher<Document> findPublisher = collection.find(new Document());
FindIterable<Document> findIterable = collection.find(new Document());
val flowInsertMany = collection .find(empty())
cursor = db.inventory.find({})
const cursor = db.collection('inventory').find({});
$cursor = $db->inventory->find([]);
cursor = db.inventory.find({})
client[:inventory].find({})
var findObservable = collection.find(Document())
If the collection does not currently exist, insert operations create the collection.
In MongoDB, each document stored in a standard collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id
field, the MongoDB driver automatically generates an ObjectId for the _id
field.
This also applies to documents inserted through update operations with upsert: true.
All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.
With write concerns, you can specify the level of acknowledgment requested from MongoDB for write operations. For more information, see Write Concern.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4