简体   繁体   中英

Script to insert JSON data into MongoDB?

I currently have a JSON file titled "data.json". In this file, I only have an array of people's names, like this:

"data":
[
    {
        {
        "name":"John",
        "age":30,
        }

        {
        "name":"Mark",
        "age":45,
        }   
    }
]

My goal is to write a script to insert this data into mongoDB. Could I write this directly in my JSON file? How would I go about this? Thanks!

You can make this script with NodeJS

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/"; // Your mongodb url here

enter code here`MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myobj = { name: "Company Inc", address: "Highway 37" };
  dbo.collection("customers").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log("The document got inserted.");
    db.close();
  });
});

You can also insert it manually through the GUI program or directly through your MongoDB command line

db.collection.insert('"data":[{"name":"John","age": 30},{"name": "Mark", "age": 45}]')

使用nodejs创建发布路线以将数据添加到mongodb中的集合

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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