admin管理员组文章数量:1181399
I wonder how I could insert array of objects to Mongo collection "root-level documents" with own pre-defined _id values.
I have tried db.MyCollection.insert(array);
but it creates nested documents under one single generated _id in MongoDB.
var array = [
{ _id: 'rg8nsoqsxhpNYho2N',
goals: 0,
assists: 1,
total: 1 },
{ _id: 'yKMx6sHQboL5m8Lqx',
goals: 0,
assists: 1,
total: 1 }];
db.MyCollection.insert(array);
What I want
I wonder how I could insert array of objects to Mongo collection "root-level documents" with own pre-defined _id values.
I have tried db.MyCollection.insert(array);
but it creates nested documents under one single generated _id in MongoDB.
var array = [
{ _id: 'rg8nsoqsxhpNYho2N',
goals: 0,
assists: 1,
total: 1 },
{ _id: 'yKMx6sHQboL5m8Lqx',
goals: 0,
assists: 1,
total: 1 }];
db.MyCollection.insert(array);
Share Improve this question edited Apr 27, 2016 at 13:00 justdiehard asked Apr 27, 2016 at 11:03 justdiehardjustdiehard 2591 gold badge2 silver badges12 bronze badges 8 | Show 3 more commentsWhat I want
3 Answers
Reset to default 15db.collection.insertMany() is what you need (supported from 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")
]
}
Why not iterate over the array objects, and insert them one at a time?
array.forEach((item) => db.MyCollection.insert(item));
You can use MongoDB Bulk to insert multiple document in one single call to the database.
First iterate over your array and call the bulk
method for each item:
bulk.insert(item)
After the loop, call execute
:
bulk.execute()
Take a look at the refereed documentation to learn more.
本文标签: javascriptInsert array of objects into MongoDBStack Overflow
版权声明:本文标题:javascript - Insert array of objects into MongoDB - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738230942a2070459.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
db.MyCollection.insert(array)
should work. Are you getting any error message? – Sede Commented Apr 27, 2016 at 11:05