猫鼬:Model.create和Collection.insert有什么区别 [英] Mongoose: what's the differences between Model.create and Collection.insert
问题描述
我想在MongoDB中做一个批量插入工作,我发现了Mongoose中的两种方法:
I want do a batch insert job in MongoDB and I found two ways in mongoose:
一种方法是使用insert
:
dataArr = [
{
id: "",
name: ""
}
{
id: "",
name: ""
}
]
Collection.insert(dataArr)
Collection.insert(dataArr)
另一种方式是Model.create
:
Model.create(dataArr)
两者都可以完成批量插入作业,但是它们之间有什么区别?
both could complete the batch insert job, but what's the difference between them?
哪个是效率更高?
推荐答案
在Mongoose中,有 Model.create
和 Collection.insert
(后者严格来说不是Mongoose的一部分,而是底层的MongoDB驱动程序).
In Mongoose, there is Model.create
and Collection.insert
(the latter isn't strictly part of Mongoose, but of the underlying MongoDB driver).
根据Mongoose开发人员的说法,当使用数组数组调用它们时,它们基本相同文档,尽管查看代码会使我认为存在细微的差异(警告:我没有很好地查看代码 ,所以我可能会误认为以下内容):
According to the Mongoose developer, they are basically the same when called with an array of documents, although looking at the code makes me think that there are subtle differences (warning: I haven't looked at the code that well so I might be mistaken about the following):
- 使用
Model.create
将调用在您的架构上声明的所有验证器/挂钩; -
Model.create
对数组中的每个文档执行.save
,从而导致N
数据库调用(其中N
是数组中的文档数);Collection.insert
执行一个大型数据库调用;
- using
Model.create
will call any validators/hooks declared on your schema; Model.create
does a.save
for each document in the array, resulting inN
database calls (whereN
is the number of documents in the array);Collection.insert
performs one large database call;
这篇关于猫鼬:Model.create和Collection.insert有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!