简体   繁体   English

将对象数组插入MongoDB

[英]Insert array of objects into MongoDB

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); 我试过db.MyCollection.insert(array); but it creates nested documents under one single generated _id in MongoDB. 但它在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(数组);

在此输入图像描述

What I want 我想要的是

在此输入图像描述

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

为什么不迭代数组对象,并一次插入一个?

array.forEach((item) => db.MyCollection.insert(item));

Go through this Link To get Exact Outcome the way you want: 浏览此链接以您希望的方式获得Exact Outcome:

https://docs.mongodb.org/manual/tutorial/insert-documents/#insert-a-document https://docs.mongodb.org/manual/tutorial/insert-documents/#insert-a-document

You can use MongoDB Bulk to 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. 查看参考文档以了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM