Insert Documents插入文件

This page provides examples in:本页提供了以下示例:

This page provides examples of insert operations in MongoDB.本页提供了MongoDB中插入操作的示例。

Creating a Collection创建集合

If the collection does not currently exist, insert operations will create the collection.如果集合当前不存在,则插入操作将创建集合。

Insert a Single Document插入单个文档

db.collection.insertOne() inserts a single document into a collection.db.collection.insertOne()将单个文档插入到集合中。

The following example inserts a new document into the inventory collection. 以下示例将新文档插入到inventory集合中。If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document. 如果文档未指定_id字段,MongoDB将向新文档添加带有ObjectId值的_id字段。See Insert Behavior.请参见插入行为

To insert a single document using MongoDB Compass:要使用MongoDB Compass插入单个文档,请执行以下操作:

  1. Navigate to the collection you wish to insert the document into:导航到要将文档插入的集合:

    1. In the left-hand MongoDB Compass navigation pane, click the database to which your target collection belongs.在左侧MongoDB Compass导航窗格中,单击目标集合所属的数据库。
    2. From the database view, click the target collection name.在数据库视图中,单击目标集合名称。
  2. Click the Insert Document button:单击“插入文档”按钮:

    ../../_images/compass-insert-button.png
  3. For each field in the document, select the field type and fill in the field name and value. 对于文档中的每个字段,选择字段类型并填写字段名称和值。Add fields by clicking the last line number, then clicking Add Field After …通过单击最后一行号添加字段,然后单击“在...后面添加字段”

    • For Object types, add nested fields by clicking the last field’s number and selecting Add Field After …对于object类型,通过单击最后一个字段的编号并选择“在...后面添加字段”来添加嵌套字段
    • For Array types, add additional elements to the array by clicking the last element’s line number and selecting Add Array Element After …对于Array类型,通过单击最后一个元素的行号并选择“在...后面添加数据元素”,将其他元素添加到数组中
  4. Once all fields have been filled out, click Insert.填写完所有字段后,单击“插入”。

The following example inserts a new document into the test.inventory collection:以下示例将新文档插入到test.inventory集合中:

pymongo.collection.Collection.insert_one() inserts a single document into a collection.

The following example inserts a new document into the inventory collection. 以下示例将新文档插入到inventory集合中。If the document does not specify an _id field, the PyMongo driver adds the _id field with an ObjectId value to the new document. 如果文档未指定_id字段,PyMongo驱动程序会将带有ObjectId值的_id字段添加到新文档中。See Insert Behavior.请参见插入行为

com.mongodb.client.MongoCollection.insertOne inserts a single document into a collection.com.mongodb.client.MongoCollection.insertOne将单个文档插入到集合中。

The following example inserts a new document into the inventory collection. 以下示例将新文档插入到inventory集合中。If the document does not specify an _id field, the driver adds the _id field with an ObjectId value to the new document. 如果文档未指定_id字段,则驱动程序会将带有ObjectId值的_id字段添加到新文档中。See Insert Behavior.请参见插入行为

Collection.insertOne() inserts a single document into a collection.Collection.insertOne()将单个文档插入到集合中。

The following example inserts a new document into the inventory collection. 以下示例将新文档插入到inventory集合中。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. 如果文档未指定_id字段,Node.js驱动程序会将带有ObjectId值的_id字段添加到新文档中。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.请参见插入行为

motor.motor_asyncio.AsyncIOMotorCollection.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 Motor driver adds the _id field with an ObjectId value to the new document. See Insert Behavior.请参见插入行为

com.mongodb.reactivestreams.client.MongoCollection.insertOne inserts a single document into a collection with the Java Reactive Streams Driver:

{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }

The following example inserts the document above 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.请参见插入行为

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.请参见插入行为

MongoDB::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 Perl 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.请参见插入行为

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.请参见插入行为

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

You can run the operation in the web shell below:您可以在下面的web shell中运行该操作:

../../_images/compass-insert-document-inventory.png
db.inventory.insert_one(
    {"item": "canvas",
     "qty": 100,
     "tags": ["cotton"],
     "size": {"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);

collection.insertOne(canvas);
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'],
]);
await db.inventory.insert_one(
    {"item": "canvas",
     "qty": 100,
     "tags": ["cotton"],
     "size": {"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);
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);
$db->coll("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()
result, err := coll.InsertOne(
	context.Background(),
	bson.D{
		{"item", "canvas"},
		{"qty", 100},
		{"tags", bson.A{"cotton"}},
		{"size", bson.D{
			{"h", 28},
			{"w", 35.5},
			{"uom", "cm"},
		}},
	})

insertOne() returns a document that includes the newly inserted document’s _id field value. insertOne()返回包含新插入文档的_id字段值的文档。For an example of a return document, see db.collection.insertOne() reference.有关返回文档的示例,请参阅db.collection.insertOne()参考

Note

MongoDB Compass generates the _id field and its value automatically. MongoDB Compass自动生成_id字段及其值。The generated ObjectId consists of a unique randomly generated hexadecimal value.生成的ObjectId由唯一的随机生成的十六进制值组成。

You can change this value prior to inserting your document so long as it remains unique and is a valid ObjectId. 您可以在插入文档之前更改此值,只要它保持唯一且是有效的ObjectIdFor more information on the _id field, see _id Field.有关_id字段的详细信息,请参阅_id字段

insert_one() returns an instance of pymongo.results.InsertOneResult whose inserted_id field contains the _id of the newly inserted document.

insertOne() returns a promise that provides a result. insertOne()返回提供结果的承诺。The result.insertedId promise contains the _id of the newly inserted document.result.insertedId承诺包含新插入文档的_id

Upon successful insert, the insertOne() method returns an instance of MongoDB\InsertOneResult whose getInsertedId() method returns the _id of the newly inserted document.

insert_one() returns an instance of pymongo.results.InsertOneResult whose inserted_id field contains the _id of the newly inserted document.

com.mongodb.reactivestreams.client.MongoCollection.insertOne returns a Publisher object. The Publisher inserts the document into a collection when subscribers request data.

Upon successful insert, the insert_one() method returns an instance of MongoDB::InsertOneResult whose inserted_id attribute contains the _id of the newly inserted document.

Upon successful insert, the insert_one() method returns an instance of Mongo::Operation::Result, whose inserted_id attribute contains the _id of the newly inserted document.

Upon successful insert, the collection.insertOne() method returns an instance of collection.insertOne().results(); whose inserted_id attribute contains the _id of the newly inserted document.

Collection.InsertOne function returns an instance of InsertOneResult whose InsertedID attribute contains the _id of the newly inserted document.Collection.InsertOne函数返回InsertOneResult的实例,其InsertedID属性包含新插入文档的_id

To retrieve the document that you just inserted, query the collection:要检索刚插入的文档,请查询集合

db.inventory.find( { item: "canvas" } )
../../_images/compass-query-collection.png

Specify a filter in the MongoDB Compass query bar and click Find to execute the query.在MongoDB Compass查询栏中指定一个过滤器,然后单击“Find”执行查询。

The above filter specifies that MongoDB Compass only return documents where the item field is equal to canvas.上面的过滤器指定MongoDB Compass仅返回item字段等于画布的文档。

For more information on the MongoDB Compass Query Bar, see the Compass Query Bar documentation.有关MongoDBCompass查询栏的更多信息,请参阅Compass查询栏文档。

cursor = db.inventory.find({"item": "canvas"})
FindIterable<Document> findIterable = collection.find(eq("item", "canvas"));
const cursor = db.collection('inventory').find({ item: 'canvas' });
$cursor = $db->inventory->find(['item' => 'canvas']);
cursor = db.inventory.find({"item": "canvas"})
FindPublisher<Document> findPublisher = collection.find(eq("item", "canvas"));
var filter = Builders<BsonDocument>.Filter.Eq("item", "canvas");
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { item => "canvas" } );
client[:inventory].find(item: 'canvas')
val observable = collection.find(equal("item", "canvas"))
cursor, err := coll.Find(
	context.Background(),
	bson.D{{"item", "canvas"}},
)

Insert Multiple Documents插入多个文档

New in version 3.2.版本3.2中的新功能。

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. 以下示例将三个新文档插入到inventory集合中。If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document. 如果文档没有指定_id字段,MongoDB会向每个文档添加带有ObjectId值的_id字段。See Insert Behavior.请参见插入行为

Currently, MongoDB Compass does not support inserting multiple documents in a single operation.目前,MongoDB Compass不支持在一次操作中插入多个文档。

New in version 3.2.版本3.2中的新功能。

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. 以下示例将三个新文档插入到inventory集合中。If the documents do not specify an _id field, the PyMongo driver adds the _id field with an ObjectId value to each document. 如果文档未指定_id字段,PyMongo驱动程序将向每个文档添加带有ObjectId值的_id字段。See Insert Behavior.请参见插入行为

New in version 3.2.版本3.2中的新功能。

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. 以下示例将三个新文档插入到inventory集合中。If the documents do not specify an _id field, the driver adds the _id field with an ObjectId value to each document. 如果文档未指定_id字段,则驱动程序会将带有ObjectId值的_id字段添加到每个文档中。See Insert Behavior.请参见插入行为

New in version 3.2.版本3.2中的新功能。

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. 以下示例将三个新文档插入到inventory集合中。If the documents do not specify an _id field, the Node.js driver adds the _id field with an ObjectId value to each document. 如果文档没有指定_id字段,Node.js驱动程序会将带有ObjectId值的_id字段添加到每个文档中。See Insert Behavior.请参见插入行为

New in version 3.2.版本3.2中的新功能。

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.请参见插入行为

motor.motor_asyncio.AsyncIOMotorCollection.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.请参见插入行为

New in version 3.2.版本3.2中的新功能。

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.请参见插入行为

New in version 3.2.版本3.2中的新功能。

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.请参见插入行为

New in version 3.2.版本3.2中的新功能。

MongoDB::Collection::insert_many() can insert multiple documents into a collection. Pass an array reference 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 Perl driver adds the _id field with an ObjectId value to each document. See Insert Behavior.请参见插入行为

New in version 3.2.版本3.2中的新功能。

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.请参见插入行为

New in version 3.2.版本3.2中的新功能。

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.请参见插入行为

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.请参见插入行为

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" } }
])

You can run the operation in the web shell below:您可以在下面的web shell中运行该操作:

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"}}])
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));
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'],
    ],
]);
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"}}])
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));
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);
$db->coll("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()
result, err := coll.InsertMany(
	context.Background(),
	[]interface{}{
		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"},
			}},
		},
	})

insertMany() returns a document that includes the newly inserted documents _id field values. 返回包含新插入的文档_id字段值的文档。See the reference for an example.有关示例,请参阅参考资料

To retrieve the inserted documents, query the collection:要检索已插入的文档,请查询集合

insert_many() returns an instance of pymongo.results.InsertManyResult whose inserted_ids field is a list containing the _id of each newly inserted document.

To retrieve the inserted documents, query the collection:

To retrieve the inserted documents, query the collection:

insertMany() returns a promise that provides a result. 返回提供result的承诺。The result.insertedIds field contains an array with the _id of each newly inserted document.result.insertedIds字段包含一个数组,其中包含每个新插入文档的_id

To retrieve the inserted documents, query the collection:要检索已插入的文档,请查询集合

Upon successful insert, the insertMany() method returns an instance of MongoDB\InsertManyResult whose getInsertedIds() method returns the _id of each newly inserted document.

To retrieve the inserted documents, query the collection:

insert_many() returns an instance of pymongo.results.InsertManyResult whose inserted_ids field is a list containing the _id of each newly inserted document.

To retrieve the inserted documents, query the collection:

com.mongodb.reactivestreams.client.MongoCollection.html.insertMany returns a Publisher object. The Publisher inserts the document into a collection when subscribers request data.

To retrieve the inserted documents, query the collection:

To retrieve the inserted documents, query the collection:

Upon successful insert, the insert_many() method returns an instance of MongoDB::InsertManyResult whose inserted_ids attribute is a list containing the _id of each newly inserted document.

To retrieve the inserted documents, query the collection:

Upon successful insert, the insert_many() method returns an instance of Mongo::BulkWrite::Result whose inserted_ids attribute is a list containing 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:

To retrieve the inserted documents, query the collection:

db.inventory.find( {} )
../../_images/compass-select-all.png
cursor = db.inventory.find({})
FindIterable<Document> findIterable = collection.find(new Document());
const cursor = db.collection('inventory').find({});
$cursor = $db->inventory->find([]);
cursor = db.inventory.find({})
FindPublisher<Document> findPublisher = collection.find(new Document());
var filter = Builders<BsonDocument>.Filter.Empty;
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( {} );
client[:inventory].find({})
var findObservable = collection.find(Document())
cursor, err := coll.Find(
	context.Background(),
	bson.D{},
)

Insert Behavior插入行为

Collection Creation集合创建

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. 在MongoDB中,存储在集合中的每个文档都需要一个唯一的_id字段作为主键If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.如果插入的文档省略了_id字段,MongoDB驱动程序会自动为_id字段生成ObjectId

This also applies to documents inserted through update operations with upsert: true.这也适用于通过upsert:true的更新操作插入的文档。

Atomicity原子性

All write operations in MongoDB are atomic on the level of a single document. MongoDB中的所有写操作都是单个文档级别的原子操作。For more information on MongoDB and atomicity, see Atomicity and Transactions有关MongoDB和原子性的更多信息,请参阅原子性和事务

Write Acknowledgement写确认

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. 对于写操作,您可以指定MongoDB为写操作请求的确认级别。For details, see Write Concern.有关详细信息,请参阅写关注事项