在滤波器定义构建器中,将对象施放在蒙哥多B文档中的日期时间

发布于 2025-01-22 17:17:50 字数 871 浏览 0 评论 0原文

我希望有人可以帮助我,因为我是Mongo DB的新手或将我指向工作,我在Mongo DB文档中有一个属性,但这是一个日期,我想成为能够通过LTE和GTE过滤器过滤。下面的示例是一个简化的示例,但是我无法更改数据库中的类型,我需要弄清楚如何在过滤器上将对象施放到日期时间,以便可以将其与另一个。

public class Happy
{
    public ObjectId Id { get; set; }
    public object DateStr { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var db = new MongoClient("mongodb://127.0.0.1:27017").GetDatabase("Test");
        var dbCollection = db.GetCollection<Happy>(nameof(Happy));

        dbCollection.InsertOne(new Happy { DateStr = DateTime.Now.ToString(CultureInfo.InvariantCulture) });
        dbCollection.InsertOne(new Happy { DateStr = DateTime.Now.ToString(CultureInfo.InvariantCulture) });

        var test = dbCollection.FindAsync(Builders<Happy>.Filter.Lte(x => (DateTime)x.DateStr, DateTime.Now)).Result.ToList();
    }
}

I am hoping someone can help me as I am new to Mongo DB or point me to a work around, I have a property within a Mongo DB document which is of type object, but it is a date time, and I would like to be able to filter it by a Lte and Gte filter. The below example is a simplified example, but I cannot change the type in the database, I need to figure out how to on the filter cast the object to Date time so it can be compared with another.

public class Happy
{
    public ObjectId Id { get; set; }
    public object DateStr { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var db = new MongoClient("mongodb://127.0.0.1:27017").GetDatabase("Test");
        var dbCollection = db.GetCollection<Happy>(nameof(Happy));

        dbCollection.InsertOne(new Happy { DateStr = DateTime.Now.ToString(CultureInfo.InvariantCulture) });
        dbCollection.InsertOne(new Happy { DateStr = DateTime.Now.ToString(CultureInfo.InvariantCulture) });

        var test = dbCollection.FindAsync(Builders<Happy>.Filter.Lte(x => (DateTime)x.DateStr, DateTime.Now)).Result.ToList();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

骑趴 2025-01-29 17:17:50

我建议将DateTime存储为“ dateTime.now.touniversaltime()”

,然后像这样查询

  Builders<Model>.Filter.Lte(x => (DateTime)x.DateStr, DateTime.Now.AddDays(1));

I would suggest storing the Datetime as "DateTime.Now.ToUniversalTime()"

and then query it like this

  Builders<Model>.Filter.Lte(x => (DateTime)x.DateStr, DateTime.Now.AddDays(1));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文