gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:58:31 24 4
gpt4 key购买 nike

我正在构建一个需要将数据从 MongoDB 文档传输到 SQL Server 表的应用程序。我正在创建一个用于将 MongoDB 文档导出到其中的 JSON 文件(其代码已随附)。我现在如何添加过滤器,以便只有在将特定数据重新导出到 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 日期时间进行过滤:

// 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包

关于c# - 如何在 C# 中使用 ObjectId 中的时间戳过滤文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55370481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com