如何从C#Mongodb Driver查询Timestamp字段?

时间:2013-07-30 12:14:07

标签: mongodb c#-4.0 mongodb-.net-driver

我在本地数据库中有一个名为“oplog.rs”的集合,它具有带时间戳字段类型的“ts”。数据存储如下:

{ 
    "ts" : Timestamp(1374672101000, 1), 
    "h" : NumberLong(0), 
    "v" : 2, 
    "op" : "n",
    "ns" : "", 
    "o" : { "msg" : "initiating set" } 
}

如何从C#驱动程序查询Timestamp字段?

这是“opslog”集合中的数据:

{ "ts" : Timestamp(1375198013000, 1), "h" : NumberLong("-4582872941246748867"),"v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198012000, 5), "h" : NumberLong("2189325868256500260"), "v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198012000, 4), "h" :NumberLong("-4649577771618475915"),"v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ...} }
{ "ts" : Timestamp(1375198012000, 3), "h" : NumberLong("9039523732738063755"), "v" : 2, "op" : "i", "ns" :"audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198012000, 2), "h" :NumberLong("8432711896209033544"), "v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198012000, 1), "h" : NumberLong("8059694251326474562"), "v" : 2, "op" : "i", "ns" :"audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198011000, 5), "h" : NumberLong("8581369985048440971"), "v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198011000, 4), "h" : NumberLong("-1142902968129950222"),"v" : 2, "op" : "i", "ns" :"audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198011000, 3), "h" : NumberLong("-4104381148312926566"),"v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198011000, 2), "h" : NumberLong("-1413662537726747267"),"v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198011000, 1), "h" :NumberLong("-1031425920752689991"),"v" : 2, "op" : "i", "ns" : "audit.search", "o" : { ... } }
{ "ts" : Timestamp(1375198010000, 1), "h" : NumberLong("12432179788117176"), "v" : 2, "op" : "i", "ns" :"audit.search", "o" : { ... } }

我有2个查询:

{ "ts" : { "$lte" : NumberLong("5906428099062398977") } }

{ "ts" : { "$gte" : NumberLong("5906428099062398977") } }

第一个查询是返回结果,但第二个查询不返回任何结果。 为什么“$ gte”运算符不起作用?

1 个答案:

答案 0 :(得分:2)

您需要使用BsonTimestamp班级(docs)。

public class OpsLog {
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonElement("ts")] // use the abbreviation in serialization
    public BsonTimestamp TimeStamp{ get; set; }
    // etc...
}

您可以使用构造函数创建一个实例来查询它,该构造函数传入一个表示时间戳的长数字:

var query = Query.EQ("ts", new BsonTimeStamp(timestampValue));
var cursor = myCollection.FindAs<OpsLog>(query);
foreach(var log in cursor) {
    // etc...
}