简体   繁体   English

如何在mongodb中使用_id(字符串)作为_id(objectId)导入json文件?

[英]How to import a json file with _id (string) as _id (objectId) in mongodb?

I have an array which has multiple objects and objects have _id (string) already set. 我有一个数组有多个对象和对象已设置_id(字符串)。 While I import the file, i want all _id (string) to get imported into _id (objectId). 当我导入文件时,我希望所有_id(字符串)都导入_id(objectId)。

I have tried manually using "$oid" but it is not a dynamic solution to my problem. 我试过手动使用“$ oid”,但它不是我的问题的动态解决方案。

my import statement 我的进口声明

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

my example object 我的示例对象

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

You can use the ObjectId() method available in mongoDB shell which returns a new ObjectId value 您可以使用mongoDB shell中提供的ObjectId()方法,该方法返回一个新的ObjectId值

Your object will look like this 你的对象看起来像这样

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

Try importing to a temporary collection & inserting it from there, 尝试导入临时集合并从那里插入,

in your case, 在你的情况下,

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

From mongo shell 来自mongo shell

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

Note: The answer was seen somewhere before, wasn't able to find in stackoverflow, may be some forums. 注意:答案之前曾在某处看过,无法在stackoverflow中找到,可能是某些论坛。

You can make a node.js script for doing import 您可以创建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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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