2016-03-01 63 views
0

我想複製集合中的某些數據。例如這樣的查詢的結果;複製集合中的某些項目

db.collection("test").find({tag: "ABC"}); 

其結果爲;

{"_id" : "1","tag" : "ABC"} 
{"_id" : "2","tag" : "ABC"} 

我想複製這兩個項目,並創建新的項目與新ID。

我該怎麼辦呢?

1.我認爲我可以做到;

db.collection("test").find({"tag": "ABC"}).each(function(err, item) { 
    //insert each item with a new id 

} 

但有沒有更好的方法來複制與查詢集合?

澄清;

因此我想擁有;

{"_id" : "v1_1","tag" : "ABC"} 
{"_id" : "v1_2","tag" : "ABC"} 
{"_id" : "1","tag" : "ABC"} 
{"_id" : "2","tag" : "ABC"} 
+0

還不清楚你想在這裏做什麼;你想複製一些數據,有什麼數據?你的意思是複製到另一個集合? – chridam

+0

no no。在同一個集合中。我想複製集合中的項目。 – sergerde

回答

0

我只能想到這個解決方案:

db.collection("test").find({"tag": "ABC"}).each(function(err, items) { 
    if(err) console.log("Error : " + err); 
    if(items){ 
     db.collection("test").insert(items, function(err, items){ 
      if(err) console.log("Error: " + err); 
      if(items) console.log("Data inserted successfully"); 
     }); 
    } 
} 

我不知道是否有比這更好的解決方案。

相關問題