查询从Mongodb获取与所有列匹配的数据

时间:2014-09-04 17:22:14

标签: c# mongodb

我在mongodb中有如下所示的文件。请告诉我如何在C#中获取与域名,主机名和服务(所有三个字段应该匹配)相匹配的最新文档。

{
    "_id" : ObjectId("53e1373e9c2e1805dd895cbd"),
    "service" : "RAM__Usage",
    "timestamp" : ISODate("2014-08-08T19:59:47.913Z"),
    "hostname" : "HOSTXYZ",
    "Domain" : "DOMXYZ"
}
{
    "_id" : ObjectId("53e1373e9c2e1805dd895abd"),
    "service" : "RAM__Usage",
    "timestamp" : ISODate("2014-09-09T19:59:47.913Z"),
    "hostname" : "HOSTXYZ",
    "Domain" : "DOMXYZ"
}
{
    "_id" : ObjectId("53e1373e9c2e1805dd895abe"),
    "service" : "CPU__Usage",
    "timestamp" : ISODate("2014-09-09T19:59:47.913Z"),
    "hostname" : "HOSTXYZ",
    "Domain" : "DOMXYZ"
}
{
    "_id" : ObjectId("53e1373e9c2e1805dd895aff"),
    "service" : "RAM__Usage",
    "timestamp" : ISODate("2014-06-06T19:59:47.913Z"),
    "hostname" : "HOSTABC",
    "Domain" : "DOMABC"
}
{
    "_id" : ObjectId("53e1373e9c2e1805dd895agc"),
    "service" : "CPU__Usage",
    "timestamp" : ISODate("2014-07-07T19:59:47.913Z"),
    "hostname" : "HOSTABC",
    "Domain" : "DOMABC"
}

1 个答案:

答案 0 :(得分:0)

解决方案:

    var query = Query.And(Query.EQ("Domain", "DOMXYZ"), Query.EQ("hostname", "HOSTXYZ"), Query.EQ("service", "RAM_USAGE"));

   //Gets the latest record from MongoDB matching given fileds
    var bsonCursor = GetMongoDatabase().GetCollection<YourClassName(YourMongoDBCollectionName).Find(query).SetSortOrder(SortBy.Descending("timestamp")).SetLimit(1);

    foreach (YourClassName objYourClassName in bsonCursor)
    {
        //Do your task
    }