【问题标题】:Samus Mongodb-csharp Inserting Dates & Querying by DatesSamus Mongodb-csharp 插入日期 & 按日期查询
【发布时间】:2011-04-10 08:37:10
【问题描述】:

我正在使用 MongoDB-Csharp 驱动程序,我想知道插入和查询日期字段的正确方法是什么?

我尝试使用 System.DateTime 存储日期,但是当我尝试按日期查询时遇到问题。

示例:

插入数据

var mongo = new Mongo();
var db = mongo.GetDatabase(dbName);
var collection = db.GetCollection(collectionName);

var document = new Document();
document["date"] = DateTime.Now.ToUniversalTime();
collection.Save(document);

查询数据

var mongo = new Mongo();
var db = mongo.GetDatabase(dbName);
var collection = db.GetCollection(collectionName);
var results = collection.Find(
new Document()
{
    {
        "date",
        new Document()
        {
            {
                "$lte", DateTime.Now.ToUniversalTime()
            }
        }
    }
}
);

【问题讨论】:

  • 看起来不错。究竟是什么问题?没有结果吗?
  • 感谢您的浏览!我的错,我实际上是在使用 shell 插入数据。当我运行上面的代码时,它确实有效。所以,这可能是一个附带问题,但是日期需要如何保存在 MongoDB shell 中?

标签: datetime mongodb mongodb-.net-driver


【解决方案1】:

由于 MongoDB shell 是 JavaScript shell,你需要使用the JavaScript Date object

db.datetest.insert({"event": "New Year's Day 2011", "date": new Date(2011, 0, 1)});
db.datetest.insert({"event": "Now", "date": new Date()});

请注意,如果您将年、月、日传递给构造函数,则月份从 0 开始。

您也可以将字符串传递给它的构造函数,但它似乎忽略了语言环境,因此您的日期需要采用美式格式:

db.datetest.insert({"event": "Christmas Day 2010", "date": new Date('12/25/2010')});

请务必使用new Date() 而不仅仅是Date(),因为Date() 只返回一个字符串,您将无法将其作为日期查询。

MongoDB-CSharp 驱动程序在将 .NET DateTime 对象序列化为 BSON 时会将其转换为 MongoDB Date 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多