繁体   English   中英

如何在C#中使用ObjectId中的时间戳过滤文档?

[英]How do I filter documents using the timestamp in ObjectId in C#?

我正在构建一个需要将数据从MongoDB文档传输到SQL Server表的应用程序。 我正在创建一个JSON文件,用于将MongoDB文档导出到其中(已随其附上了代码)。 现在如何添加一个过滤器,以便仅将在将特定数据导出到JSON之后在MongoDB集合中创建的文档?

我相信可以通过某种方式使用MongoDB文档的ObjectId字段中的时间戳来实现,但无法找到方法。

using (FileStream fs = File.Create(path))
{
    using (var fw = new StreamWriter(fs))
    {
        fw.Write("[");
            using (var cursor = await collection.Find(new BsonDocument()).Project(Builders<BsonDocument>.Projection.Exclude("_id")).ToCursorAsync())
            {
            while (await cursor.MoveNextAsync())

                foreach (var doc in cursor.Current)
                {
                    fw.Write(doc.ToString());
                    fw.Write(",");
                }
                fw.Flush();
        }
        fs.SetLength(fs.Length - 1);
        fw.Write("]");
    }
}

我无法使用您的确切示例,但是我设法使用ObjectId datetime创建了类似的过滤器:

// Declare a date range - presumably these would be dynamic not fixed strings
var startDateTime = DateTime.Parse("2018-09-13 14:19:26.000Z");
var endDateTime = DateTime.Parse("2018-09-24 14:03:38.000Z");

// Use the dates to create ObjectId type for comparison
var startId = new ObjectId(startDateTime, 0, 0, 0);
var endId = new ObjectId(endDateTime, 0, 0, 0);

// Use the ObjectId types in the filter
using (var cursor = await collection.Find(x => x._id > startId && x._id < endId).ToCursorAsync())
{
    while (await cursor.MoveNextAsync())
    {
        foreach (var doc in cursor.Current)
        {
            // Use doc object
        }
     }
 }

注意:我使用了最新的MongoDB.Driver包

在上面的代码片段中,使用StreamWriter构建了一个JSON文件,然而,可以通过C#应用程序代码使用mongoexport.exe进程来解决此目的,这也使过滤更加容易:

public static string dateConverter(DateTime dt)
    {
        long decimalNumber = (long)(dt.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        return (Convert.ToString(decimalNumber, 16));
    }
public static void Main(string[] args)
    {
        try
        {
            CultureInfo provider = CultureInfo.InvariantCulture;
            string instr;
            Console.WriteLine("Enter the start date");
            instr = Console.ReadLine();
            DateTime.TryParseExact(instr, "yyyy/MM/dd", provider, DateTimeStyles.None, out startDate);
            Console.WriteLine("Enter the end date");
            instr = Console.ReadLine();
            DateTime.TryParseExact(instr, "yyyy/MM/dd", provider, DateTimeStyles.None, out endDate);
            queryFilter = "{_id:{$gte: ObjectId('" + dateConverter(startDate) + "0000000000000000'), $lte: ObjectId('" + dateConverter(endDate) + "ffffffffffffffff')}}";
            string expstring = " --db yourDatabaseName --collection yourCollectionName --type json --query " + queryFilter + " --out yourFilePath --jsonArray";
            Process export = new Process();
            export.StartInfo.FileName = ExportEXEPath;
            export.StartInfo.Arguments = expstring;
            export.Start();
        }
        catch (Exception ex)
        {
            Console.WriteLine("[ERROR]: " + ex.Message);
        }
    }

但是,使用在其内部包含双引号(“)的字符串将参数传递到命令行存在一个问题(如--query关键字之后所做的那样),对此的讨论可以由点击这里

暂无
暂无

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

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