【问题标题】:How to import a json file with _id (string) as _id (objectId) in mongodb?如何在mongodb中导入带有_id(字符串)作为_id(objectId)的json文件?
【发布时间】:2019-06-01 00:15:31
【问题描述】:

我有一个包含多个对象的数组,并且对象已经设置了 _id(字符串)。当我导入文件时,我希望将所有 _id(字符串)导入到 _id(objectId)中。

我尝试过手动使用“$oid”,但这不是我问题的动态解决方案。

我的进口声明

mongoimport --db delivera --collection restaurants --drop --file list.json --jsonArray

我的示例对象

{
"_id":"5a6900fff467be65019a9001",
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    尝试导入到临时集合并从那里插入,

    在你的情况下,

    mongoimport --db myApp --collection tempCollection --drop --file list.json --jsonArray
    

    来自 mongo 外壳

    db.tempCollection.find().forEach(function (doc) {
        doc._id = doc._id + ''
        db.restaurants.insert(doc)
    });
    

    注意:答案之前在某个地方看到过,在stackoverflow中找不到,可能是一些论坛。

    【讨论】:

      【解决方案2】:

      您可以制作一个 node.js 脚本来进行导入

      var MongoClient = require('mongodb').MongoClient;
      var ObjectID = require('mongodb').ObjectID;
      var url = "mongodb://localhost:27017/delivera"; //host and db
      var file = require('./myfile.json');
      
      MongoClient.connect(url, {useNewUrlParser: true }, function(err, db) {
          var dbo = db.db("delivera"); //db
          file.map(elem => {
              elem._id = ObjectID(elem._id)
              dbo.collection("restaurants").insertOne(elem, function(err, res) { //collection
                  if (err) throw err;
              });
          })
          console.log("done")
          db.close();
      });
      
      

      【讨论】:

        【解决方案3】:

        您可以使用 mongoDB shell 中可用的 ObjectId() 方法,该方法返回一个新的 ObjectId 值

        您的对象将如下所示

        {
        "_id": Object("5a6900fff467be65019a9001"),
        "date":"2018-01-24T21:56:15.353Z",
        "title":"Italian pasta",
        "restaurant": "coffee bean",
        "__v":0
        }
        

        【讨论】:

          猜你喜欢
          • 2018-06-25
          • 2019-03-12
          • 1970-01-01
          • 2021-03-18
          • 2015-01-16
          • 2018-12-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多