我建議,如果這是你獲得Node.JS安裝和使用的代碼,如果像遵循一個時間的事情你有很多預先存在的類似JSON的文件要加載(你的語法實際上是JavaScript)。雖然我不瞭解你的數據模型(並且稍微改變了它以便編譯),但基本上我所做的只是創建一個變量,其中包含所添加的所有「變量」的數組。
通過將它們放入單個數組中,然後可以調用MongoDB的insert
方法一次插入大量文檔。回調是文檔(設置了它們的_id
字段)。如果您有成千上萬的文檔,則可能需要使用JavaScript的數組slice
將數組拆分爲更小的塊,以便在驅動器超時時不會導致超大的insert
。
var mongo = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var allVariables = [ {
ThingsToGet: [
{
first_thing: "SOMETHING ONE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING TWO",
second_thing: [[1, 0], [2, 5], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING THREE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, 2], [6, 2]],
third_thing: 0,
fourth_thing: []
},
]
}
,
{
ThingsToGet: [
{
first_thing: "SOMETHING ONE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING TWO",
second_thing: [[1, 0], [2, 5], [3, 4], [4, 4], [5, "x"], [6, "x"]],
third_thing: 0,
fourth_thing: []
},{
first_thing: "SOMETHING THREE",
second_thing: [[1, 0], [2, 0], [3, 4], [4, 4], [5, 2], [6, 2]],
third_thing: 0,
fourth_thing: []
},
]
}
];
mongo.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('variables');
// you may want to do them in batches rather than all at once
collection.insert(allVariables, function(err,docs){
if(err) throw err;
if(docs) {
console.log("Docs inserted: " + docs.length)
// you could do something here with the docs
}
});
});
另一種選擇將是實際使用json-decode
(docs)功能在PHP中加載JSON,然後插入使用MongoDB的PHP驅動程序文件。您需要將您的JSON文件的語法更改爲純粹的JSON。例如,它不能在文件中有變量聲明。
它可能會去是這樣的:
$bigJsonFile = file_get_contents('./variables.json', false)
$bigJsonObject = json_decode($json)
$collection->insert($bigJsonObject)
這是一次性的事情或東西,你經常想幹什麼? – WiredPrairie
這個項目看起來很實用,即使它有點奇怪,如果這就是你的意思。這些變量有成千上萬。 – jthomasbailey
不,你需要頻繁插入使用JSON語法嗎?如果沒有,我建議你使用Node.JS將數據插入到JSON格式中,然後使用PHP進行查詢。 – WiredPrairie