2015-04-23 115 views
2

我想在MongoDB中使用PyMongo進行批量插入。 我有數百萬個產品/評論文檔要插入到MongoDB中。這裏是文件的結構:如何在MongoDB中追加子文檔?

{ 
    "_id" : ObjectId("553858a14483e94d1e563ce9"), 
    "product_id" : "B000GIKZ4W", 
    "product_category" : "Arts", 
    "product_brand" : "unknown", 
    "reviews" : [ 
     { 
      "date" : ISODate("2012-01-09T00:00:00Z"), 
      "score" : 3, 
      "user_id" : "A3DLA3S8QKLBNW", 
      "sentiment" : 0.2517857142857143, 
      "text" : "The ink was pretty dried up upon arrival. It was...", 
      "user_gender" : "male", 
      "voted_total" : 0, 
      "voted_helpful" : 0, 
      "user_name" : "womans_roar \"rohrra\"", 
      "summary" : "Cute stamps but came with dried up ink" 
     } 
    ], 
    "product_price" : "9.43", 
    "product_title" : "Melissa & Doug Deluxe Wooden Happy Handle Stamp Set" 
} 

對於單個產品可以有多個評論。要求是爲每個product_id插入一個文檔,並在評論數組中繼續添加更多評論作爲子文檔。你能提供一些關於如何實現這一點的指示嗎?此外,將執行批量插入性能會很好。

回答

1

將很好地執行批量插入的性能。

在pymongo可以執行Ordered bulk write operationsUnordered Bulk Write Operations

要求是插入每PRODUCT_ID一個文檔,並保留追加更深入的審查陣列中的子文檔

可以使用update_oneupdate_many(Pymongo 3或更新)或update方法$push子文檔reviews陣列

collection.update_one({"_id": <doc_id>}, {"$push": {"reviews": <subdocument>}}) 

collection.update({"_id": <doc_id>}, {"$push": {"reviews": <subdocument>}}) 

要插入文檔的需要,如果沒有文件匹配給定標準使用upsert選項

collection.update({"_id": <doc_id>}, {"$push": {"reviews": <subdocument>}}, upsert=True) 
+0

感謝您的答覆。返回的UpdateResult對象的modified_count是None,它不會將任何數據插入到MongoDB中。我必須做一個upsert,如果沒有找到product_id,那麼我添加整個產品文檔,否則我只是將評論部分(subdocument)附加到現有產品文檔。請提出一個可以實現這一點的方法。 – Randeep

+0

@Randeep插入新文件如果'product_id'未找到使用'upsert = True'。編輯我的回答 – styvane

+0

是的,我現在明白了。它的工作:) 感謝您的及時迴應。 – Randeep