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

时间:2019-05-31 10:10:35

标签: javascript node.js mongodb mongoose

我有一个包含多个对象的数组,并且对象已设置_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
}

3 个答案:

答案 0 :(得分:0)

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

您的对象看起来像这样

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

答案 1 :(得分:0)

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

在您的情况下,

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

从mongo shell

   ////code



 $labels = array(
            'name'               => __( 'Partner' ),
            'singular_name'      => __( 'vendorpartner' ),
            'add_new'            => __( 'Add New vendorpartner' ),
            'add_new_item'       => __( 'Add New vendorpartner' ),
            'edit_item'          => __( 'Edit vendorpartner' ),
            'new_item'           => __( 'Add New vendorpartner' ),
            'view_item'          => __( 'View vendorpartner' ),
            'search_items'       => __( 'Search vendorpartner' ),
            'not_found'          => __( 'No events found' ),
            'not_found_in_trash' => __( 'No events found in trash' )
        );
        $supports = array(
            'title',
            'editor',
            'thumbnail',
            'comments',
            'revisions',
            'page-attributes'
        );
        $args = array(
            'labels'               => $labels,
            'supports'             => $supports,
            'public'               => true,
            'capability_type'      => 'post',
            'rewrite'              => array( 'slug' => 'vendorpartner' ),
            'has_archive'          => true,
            'menu_position'        => 30,
            'menu_icon'            => 'dashicons-calendar-alt',
            'register_meta_box_cb' => 'wpt_add_event_metaboxes',
        );
        register_post_type( 'vendorpartner', $args );

注意:答案是在以前某个地方看到的,在stackoverflow中找不到,也许是一些论坛。

答案 2 :(得分:0)

您可以制作一个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();
});