can‘t convert from BSON type long to Date

{
    $project: {
        year: {
            $year: "$createTime"
        },
        _id: 1,
        createTime: 1
    }
}

以上语句在查询mongodb时报错:can't convert from BSON type long to Date,截图如下:
在这里插入图片描述
原因:数据库存储的createTime为long类型,而project语句需要一个date类型,优化如下:

{
  year:{
    $year: new Date("$createTime")
  },
  _id:1,
  createTime:1
}

执行结果截图如下:
在这里插入图片描述
很明显,转化后的year字段存在错误。
继续优化如下:

{
  year:{
    $year: {
      "$add":[new Date(0),"$createTime"]
    }
  },
  _id:1,
  createTime:1
}

查询结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To convert between a model and BSON in C# with MongoDB, you can use the `BsonDocument` class and the `BsonSerializer` class from the MongoDB C# driver. To convert a model to BSON: ``` using MongoDB.Bson; using MongoDB.Bson.Serialization; public class Person { public ObjectId Id { get; set; } public string Name { get; set; } public int Age { get; set; } } Person person = new Person { Name = "John", Age = 30 }; BsonDocument bsonDocument = person.ToBsonDocument(); ``` To convert BSON to a model: ``` using MongoDB.Bson; using MongoDB.Bson.Serialization; BsonDocument bsonDocument = ... // retrieve the document from MongoDB Person person = BsonSerializer.Deserialize<Person>(bsonDocument); ``` Note that you should replace the `...` with the code that retrieves the document from MongoDB. If you need to convert a list of models to BSON, you can use `BsonArray` and `ToBsonDocumentArray`: ``` List<Person> people = new List<Person> { new Person { Name = "John", Age = 30 }, new Person { Name = "Jane", Age = 25 } }; BsonArray bsonArray = new BsonArray(people.Select(x => x.ToBsonDocument())); BsonDocument bsonDocument = new BsonDocument { { "people", bsonArray } }; ``` And to convert BSON to a list of models: ``` BsonDocument bsonDocument = ... // retrieve the document from MongoDB BsonArray bsonArray = bsonDocument["people"].AsBsonArray; List<Person> people = bsonArray.Select(x => BsonSerializer.Deserialize<Person>(x.AsBsonDocument)).ToList(); ``` Again, you should replace the `...` with the code that retrieves the document from MongoDB.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值