Insert Documents

mongo --host 127.0.0.1:27017

Insert Methods

Insert a Single Document

db.inventory.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5b56c992e96dafada0c36640")
}

To retrieve the document that you just inserted, query the collection:

db.inventory.find( { item: "canvas" } )
{ "_id" : ObjectId("5b56c992e96dafada0c36640"), "item" : "canvas", "qty" : 100, "tags" : [ "cotton" ], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } }

Insert Multiple Documents

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" } }
])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5b56c9cbe96dafada0c36641"),
                ObjectId("5b56c9cbe96dafada0c36642"),
                ObjectId("5b56c9cbe96dafada0c36643")
        ]
}

To retrieve the inserted documents, query the collection:

db.inventory.find( {} )
{ "_id" : ObjectId("5b56c992e96dafada0c36640"), "item" : "canvas", "qty" : 100, "tags" : [ "cotton" ], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } }
{ "_id" : ObjectId("5b56c9cbe96dafada0c36641"), "item" : "journal", "qty" : 25, "tags" : [ "blank", "red" ], "size" : { "h" : 14, "w" : 21, "uom" : "cm" } }
{ "_id" : ObjectId("5b56c9cbe96dafada0c36642"), "item" : "mat", "qty" : 85, "tags" : [ "gray" ], "size" : { "h" : 27.9, "w" : 35.5, "uom" : "cm" } }
{ "_id" : ObjectId("5b56c9cbe96dafada0c36643"), "item" : "mousepad", "qty" : 25, "tags" : [ "gel", "blue" ], "size" : { "h" : 19, "w" : 22.85, "uom" : "cm" } }

Insert Behavior

If the collection does not currently exist, insert operations will create the collection.

_id Field

In MongoDB, each document stored in a 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.

Atomicity

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

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.

results matching ""

    No results matching ""