Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将CSV文件导入Mongo数据库_C#_Mongodb_Csv_Import - Fatal编程技术网

C# 将CSV文件导入Mongo数据库

C# 将CSV文件导入Mongo数据库,c#,mongodb,csv,import,C#,Mongodb,Csv,Import,如果要从命令行导入CSV文件,只需使用: mongoimport -d <database> -c <collection name> --type csv --file <path to csv> --headerline 这种格式的一个缺点是我必须有整整四列——我不能保证这一点 完美的答案将包括一个解决问题的方法 如果相关:我希望导入多个CSV文件,以便在一个目录中找到每个文件-。您在cmd上使用该命令吗?我建议您使用StreamWriter创建一个.b

如果要从命令行导入CSV文件,只需使用:

mongoimport -d <database> -c <collection name> --type csv --file <path to csv> --headerline
这种格式的一个缺点是我必须有整整四列——我不能保证这一点

完美的答案将包括一个解决问题的方法


如果相关:我希望导入多个CSV文件,以便在一个目录中找到每个文件-。

您在cmd上使用该命令吗?我建议您使用
StreamWriter
创建一个.bat文件,然后使用
Process.Start()
执行该.bat文件,并将文件名作为参数传递给它

更好的方法:要在命令行上执行,请使用以下代码段

string command = ""; //enter any command you want
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C " + command;
process.StartInfo = startInfo;
process.Start();

我用CSVHelper读了它。PM控制台->

我分三节课做过:

  • Program.cs(在这里我读取实际的.csv并调用对象创建类)
  • Products.cs(收集详细信息和.csv列必须相同)
  • Mongo.cs(连接到MongoDB并插入或更新文档)
Program.cs:

using CsvHelper;
using System;
using System.IO;
using System.Linq;

namespace DataImport
{
    class Program
    {
        static void Main(string[] args)
        {
            // .CSV file path
            Console.WriteLine("Absolute path to .csv file: ");
            string csvFilePath = Console.ReadLine();

            // Reading .csv file line by line and calling for SendingRecord method
            using (var reader = new StreamReader(csvFilePath))
            using (var csv = new CsvReader(reader))
        {
            csv.Configuration.HasHeaderRecord = false; // My file has no header lines, if yours have this must be 'true'
            csv.Configuration.ShouldSkipRecord = record => record.All(string.IsNullOrEmpty); // Skipping empty lines in .CSV file
            var records = csv.GetRecords<Products>().ToList();
            for (int i = 0; i < records.Count; i++)
            {
                Mongo.SendingRecord(records[i]);
            }
        }
    }
}
使用CsvHelper;
使用制度;
使用System.IO;
使用System.Linq;
命名空间数据导入
{
班级计划
{
静态void Main(字符串[]参数)
{
//.CSV文件路径
WriteLine(“到.csv文件的绝对路径:”);
字符串csvFilePath=Console.ReadLine();
//逐行读取.csv文件并调用SendingRecord方法
使用(var reader=newstreamreader(csvFilePath))
使用(var csv=新的CsvReader(读卡器))
{
csv.Configuration.HasHeaderRecord=false;//我的文件没有头行,如果您有头行,则必须为“true”
csv.Configuration.ShouldSkipRecord=record=>record.All(string.IsNullOrEmpty);//跳过.csv文件中的空行
var records=csv.GetRecords().ToList();
for(int i=0;i
这将创建可以单独放入mongoDB文档中的对象列表

Products.cs:

using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;

namespace DataImport
{
public class Products
{
    [Index(0)]
    public string prop1
    {
        get;
        set;
    }

    [Index(1)]
    public decimal prop2
    {
        get;
        set;
    }

    [Index(2)]
    public int prop3
    {
        get;
        set;
    }

public class ProductsMap : ClassMap<Products>
{
    public ProductsMap()
    {
        Map(m => m.prop1);
        Map(m => m.prop2);
        Map(m => m.prop3);
    }
}
使用CsvHelper.配置;
使用CsvHelper.Configuration.Attributes;
命名空间数据导入
{
公共类产品
{
[索引(0)]
公共字符串prop1
{
得到;
设置
}
[索引(1)]
公共十进制prop2
{
得到;
设置
}
[索引(2)]
公共int prop3
{
得到;
设置
}
公共类产品映射:类映射
{
公共产品MAP()
{
Map(m=>m.prop1);
Map(m=>m.prop2);
Map(m=>m.prop3);
}
}
在这里,您需要指定.csv文件的所有行并正确映射它们。索引表示excell中的行(index0=A,index1=B…)

Mongo.cs:

using MongoDB.Driver;

namespace DataImport
{
class Mongo
{
    public static void SendingRecord(Products output)
    {
        // Connecting to MongoDB
        string connectionString = "mongodb://localhost:27017";
        MongoClient mongoClient = new MongoClient(connectionString);

        // Navigating to DB and Collection
        var db = mongoClient.GetDatabase("DB-name");

        var products = db.GetCollection<Products>("Collection-Name");

        // Importing new documents or updating existing ones
        var options = new UpdateOptions();
        options.IsUpsert = true;
        products.ReplaceOne(filter: x => x.uniqueField == output.uniqueField, replacement: output, options: options);
    }
}
使用MongoDB.Driver;
命名空间数据导入
{
蒙哥班
{
公共静态无效发送记录(产品输出)
{
//连接到MongoDB
字符串连接字符串=”mongodb://localhost:27017";
MongoClient MongoClient=新的MongoClient(connectionString);
//导航到数据库和集合
var db=mongoClient.GetDatabase(“db name”);
var products=db.GetCollection(“集合名称”);
//导入新文档或更新现有文档
var options=new UpdateOptions();
options.IsUpsert=true;
products.ReplaceOne(过滤器:x=>x.uniqueField==output.uniqueField,替换:output,options:options);
}
}
这是本地主机的连接字符串。要使其工作,您需要记录至少有一个唯一的值-id、某种数字等


如果你有任何问题,请不要犹豫。直接问。

事实上,我正在考虑将其作为一个备份计划。但我认为必须有一种方法可以直接在
C#
代码中执行?谢谢,但我更愿意直接在代码中执行。我现在可以,但我认为必须有一种更有效的方法……而不是在Bs中添加键/值对onDocument构造函数您可以创建一个包含对的字典,然后使用row.AddRange(字典)将其添加到BsonDocument。谢谢!很遗憾,我无法再验证此解决方案(我已转到一个新项目)。如果其他人确认这是有效的,我会接受。是的。我从3年前就看到了,但我尝试了2-3天,这些文档都没有真正的用处,所以当我成功做到这一点时,我决定分享。太好了,你有我的+1用于分享!希望它能帮助更多人。非常好的解决方案,很遗憾这不是选择的答案
using MongoDB.Driver;

namespace DataImport
{
class Mongo
{
    public static void SendingRecord(Products output)
    {
        // Connecting to MongoDB
        string connectionString = "mongodb://localhost:27017";
        MongoClient mongoClient = new MongoClient(connectionString);

        // Navigating to DB and Collection
        var db = mongoClient.GetDatabase("DB-name");

        var products = db.GetCollection<Products>("Collection-Name");

        // Importing new documents or updating existing ones
        var options = new UpdateOptions();
        options.IsUpsert = true;
        products.ReplaceOne(filter: x => x.uniqueField == output.uniqueField, replacement: output, options: options);
    }
}