如何使用nodejs将没有键的嵌套json数组的json文件导入到mongodb中

时间:2016-05-05 10:00:15

标签: arrays json node.js mongodb mongoose

我是Mongo的新手,想要使用嵌套的json数组导入json文件而不使用密钥,但我不知道如何解析这种格式然后导入到mongodb。让我解释一下 - >

这是我从PDF文件转换的Json文件:

[  
   [  
      "S. No.",
      "Bank Name",
      "First 4 Letters of ",
      "IFSC",
      "Short Code",
      "Multimodal Code"
   ],
   [  
      "1",
      "Abhyudaya Co-op Bank",
      "ABHY",
      "ACB",
      "*99*87#"
   ],
   [  
      "2",
      "Allahabad Bank",
      "ALLA",
      "ALB",
      "*99*54#"
   ],
   [  
      "3",
      "Andhra Bank",
      "ANDB",
      "ANB",
      "*99*59#"
   ],
   [  
      "4",
      "Apna Sahakari Bank",
      "ASBL",
      "APN",
      "*99*85#"
   ],
   [  
      "5",
      "Axis Bank",
      "UTIB",
      "AXB",
      "*99*45#"
   ]
]

现在我想使用node.js直接导入到我的mongodb中,期望第一个数组是不敬的:

[  
      "S. No.",
      "Bank Name",
      "First 4 Letters of ",
      "IFSC",
      "Short Code",
      "Multimodal Code"
 ]

好的,所以在mongodb中存储数据之后我想要查询结果的结果是这样的:

{“banks”: [ 
 {“name”: “Abhyudaya Co-op Bank”,  “ifsc”: “ABHY”, “sc”: “ACB”},
 {“name”: “Allahabad Bank”,  “ifsc”: “ALLA”, “sc”: “ALB”}, 
 {“name”: “Andhra Bank”,  “ifsc”: “ANDB”, “sc”: “ANB”},
 {“name”: “Apna Sahakari Bank”,  “ifsc”: “ASBL”, “sc”: “APN”},
 {“name”: “Axis Bank”,  “ifsc”: “UTIB”, “sc”: “AXB”}
 ]}

请帮我使用node.js代码或查询在mongo中导入此文件。

1 个答案:

答案 0 :(得分:0)

试试这个。我只做了两个参数,请相应地放其他参数。将代码放在.js文件中。我想你必须已经在数据库中使用_id:0(我在这里匹配)和“banks”:[]创建了一个集合'tmp'(或你想要的)。我试着将doc.length放在for循环中,不知何故它没有用,所以我把5放在那里。你可以试试。几秒钟后检查“tmp”集合,即使node命令没有在node.js shell中结束

var MongoClient = require('mongodb').MongoClient;var assert = require('assert');var ObjectId = require('mongodb').ObjectID;var url = 'mongodb://localhost:27017/test';var insertDocument = function(db, callback) {

doc = "put your doc here"
for (i = 1; i <= 5; i++){var a =  doc[i][1];var b =  doc[i][2];db.collection('tmp').update({_id:0},{ "$push" : {"banks" :{"name": a,"ifsc": b}}});}; } 

MongoClient.connect(url, function(err, db) { assert.equal(null, err);insertDocument(db, function() {
  db.close();});});

enter image description here