2016-04-27 134 views
10

我想知道如何將對象數組插入到具有自己的預定義_id值的Mongo集合「根級文檔」中。將對象數組插入到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(數組);

enter image description here

我想

enter image description here

+1

'db.MyCollection.insert(陣列)'應該工作。你是否收到任何錯誤訊息? – styvane

+0

插入過程有效,我正在收集數據,但我希望在「根級別」具有對象,現在它們被插入到「0」下:{},「1」:{}等等。我想用我的_id值將所有對象作爲「根級」文檔插入 – justdiehard

+0

使用您向我們顯示的文檔,您無法獲得該結果。 – styvane

回答

0

什麼,你可以使用MongoDB Bulk到數據庫中的一個單一的通話插入多個文件。

在你的陣列的第一迭代,並調用bulk方法爲每個項目:

bulk.insert(item) 

循環後,調用execute

bulk.execute() 

在審過的文檔,看看以瞭解詳情。

3

爲什麼不能在數組對象迭代,並插入一個在一個時間?

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

我已經這樣做了,但它不讓我添加「結果/成功」功能插入 – justdiehard

0

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

輸出:

{ 
    "acknowledged" : true, 
    "insertedIds" : [ 
     ObjectId("57d6c1d02e9af409e0553dff"), 
     ObjectId("57d6c1d02323d119e0b3c0e8"), 
     ObjectId("57d6c1d22323d119e0b3c16c") 
    ] 
} 
+0

有沒有辦法「插入」許多類似於此?我想每次都推一個數組,但大多數項目都會存在 – PirateApp