Javascript 将对象数组插入 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36887928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert array of objects into MongoDB
提问by justdiehard
I wonder how I could insert array of objects to Mongo collection "root-level documents" with own pre-defined _id values.
我想知道如何使用自己的预定义 _id 值将对象数组插入到 Mongo 集合“根级文档”中。
I have tried db.MyCollection.insert(array);
but it creates nested documents under one single generated _id in MongoDB.
我已经尝试过,db.MyCollection.insert(array);
但它在 MongoDB 中的一个生成的 _id 下创建了嵌套文档。
var array = [
{ _id: 'rg8nsoqsxhpNYho2N',
goals: 0,
assists: 1,
total: 1 },
{ _id: 'yKMx6sHQboL5m8Lqx',
goals: 0,
assists: 1,
total: 1 }];
db.MyCollection.insert(array);
db.MyCollection.insert(array);
What I want
我想要的是
回答by marmor
db.collection.insertMany()is what you need (supported from 3.2):
db.collection.insertMany()是你所需要的(从 3.2 开始支持):
db.users.insertMany(
[
{ name: "bob", age: 42, status: "A", },
{ name: "ahn", age: 22, status: "A", },
{ name: "xi", age: 34, status: "D", }
]
)
output:
输出:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("57d6c1d02e9af409e0553dff"),
ObjectId("57d6c1d02323d119e0b3c0e8"),
ObjectId("57d6c1d22323d119e0b3c16c")
]
}
回答by Ikechi Michael
Why not iterate over the array objects, and insert them one at a time?
为什么不遍历数组对象,一次插入一个?
array.forEach((item) => db.MyCollection.insert(item));
回答by Shantanu Madane
Go through this Link To get Exact Outcome the way you want:
通过此链接以您想要的方式获得确切的结果:
https://docs.mongodb.org/manual/tutorial/insert-documents/#insert-a-document
https://docs.mongodb.org/manual/tutorial/insert-documents/#insert-a-document
回答by Héctor Valverde Pareja
You can use MongoDB Bulkto insert multiple document in one single call to the database.
您可以使用MongoDB Bulk在一次对数据库的调用中插入多个文档。
First iterate over your array and call the bulk
method for each item:
首先遍历您的数组并bulk
为每个项目调用该方法:
bulk.insert(item)
After the loop, call execute
:
循环后,调用execute
:
bulk.execute()
Take a look at the refereed documentation to learn more.
查看参考文档以了解更多信息。