mongoDB ドキュメント(レコード)を複数件、一度にinsertする

mongoDB ドキュメント(レコード)を複数件、一度にinsertする

mongoDBで、ドキュメント(レコード)を複数件、一度にinsertする手順を記述してます。mongo6では「Collection.insert()」は非推奨となっているので「insertMany」を使用して「insert」します。

環境

  • OS CentOS Stream release 9
  • MongoDB 6.0.2

手順

ドキュメント(レコード)を複数件、一度に「insert」するには、配列を使用します。

db.foo.insert(
[ドキュメント,ドキュメント,,,]
);

実際に、insertしてみます。

> use hoge

> db.foo.insert(
	[
      {name:'siro', age:22, gender:'f'},
	    {name:'goro', age:23, gender:'x'}
   ]
);

DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("63622cf07c4cb89d6c5c570b"),
    '1': ObjectId("63622cf07c4cb89d6c5c570c")
  }
}

2件追加されたことが確認できます。

また上記「DeprecationWarning」に記述されているようにmongo6では「Collection.insert()」は非推奨になっているようなので「insertMany」を使用します。

> db.foo.insertMany( [ 
{ name: 'siro', age: 22, gender: 'f' }, 
{ name: 'goro', age: 23, gender: 'x' }
]);

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("63622db47c4cb89d6c5c570d"),
    '1': ObjectId("63622db47c4cb89d6c5c570e")
  }
}

mongoDB5

mongoDB5では、同じ処理を行うと以下の結果が返ってきます。

BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})