使用mongoDB c#驱动程序仅按日期过滤

时间:2017-04-02 10:26:22

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

我在我的项目中使用mongoDB c#最新驱动程序,即3. +。我使用daterangepicker有不同的日期过滤条件,如今天,最后一天,昨天,本月等。

这是我的模特

public class Student
    {
        public Student()
        {
        }
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime CreatedOn { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime ModifiedOn { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

这是驱动程序代码

var server = new MongoClient(_connectionString);
var db = server.GetDatabase("Students");
var collection = db.GetCollection<Student>("student");
var filterBuilder = Builders<Student>.Filter;
var start = new DateTime(2017, 03, 29);
var end = new DateTime(2017, 03, 31);
var filter = filterBuilder.Gte(x => x.CreatedOn, new BsonDateTime(start)) &
             filterBuilder.Lte(x => x.CreatedOn, new BsonDateTime(end));
List<Student> searchResult = collection.Find(filter).ToList();

此代码工作正常但是当我选择今天的过滤器时,日期变为

var start = new DateTime(2017, 03, 31);
var end = new DateTime(2017, 03, 31);

它没有返回当天的记录。它也在计算时间。

我将日期保存为DateTime.Now。我正在查询的样本ISO日期

"CreatedOn": ISODate("2017-03-31T20:27:12.914+05:00"),
"ModifiedOn": ISODate("2017-03-31T20:27:12.914+05:00"),

这是我正在使用的日期过滤器。我应该从结束日期减去-1吗? enter image description here

需要帮助我做错了。

4 个答案:

答案 0 :(得分:6)

我相信你会对时区感到困惑,尤其是偏移部分。

MongoDb始终以UTC时间保存日期。

因此,当您查看MongoDB中的日期时间时,您必须考虑与当地时区的偏移量。

您始终会以当地时区发送日期。 Mongo C#驱动程序在持久化之前将时间从本地更改为UTC。

例如

当我使用CreatedOn = 2017-04-05 15:21:23.234(当地时区(美国/芝加哥))保存文档时,但是 当您查看DB中的文档时,您将看到ISODate("2017-04-05T20:21:23.234Z")的内容,即与UTC的本地时间偏移,即-5小时。

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]表示驱动程序在将BSON退回到您的POCO时将时间从UTC转换为本地时间。

以下是解释行为的测试用例。

代码:

class Program
{

    static void Main(string[] args)
    {
        var mongo = new MongoClient("mongodb://localhost:27017/test");
        var db = mongo.GetDatabase("test");

        db.DropCollection("students");
        db.CreateCollection("students");

        var collection = db.GetCollection<Student>("students");

        var today = DateTime.Now; //2017-04-05 15:21:23.234
        var yesterday = today.AddDays(-1);//2017-04-04 15:21:23.234

        // Create 2 documents (yesterday &  today)
        collection.InsertMany(new[]
            {
            new Student{Description = "today", CreatedOn = today},
            new Student{Description = "yesterday", CreatedOn = yesterday},
            }
         );

        var filterBuilder1 = Builders<Student>.Filter;
        var filter1 = filterBuilder1.Eq(x => x.CreatedOn, today);
        List<Student> searchResult1 = collection.Find(filter1).ToList();

        Console.Write(searchResult1.Count == 1);

        var filterBuilder2 = Builders<Student>.Filter;
        var filter2 = filterBuilder2.Eq(x => x.CreatedOn, yesterday);
        List<Student> searchResult2 = collection.Find(filter2).ToList();

        Console.Write(searchResult2.Count == 1);

    }
}

public class Student
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime CreatedOn { get; set; }
    public string Description { get; set; }
}

收藏:(通过mongo shell查看)

{
        "_id" : ObjectId("58e559c76d3a9d2cb0449d84"),
        "CreatedOn" : ISODate("2017-04-04T20:21:23.234Z"),
        "Description" : "yesterday"
}
{
        "_id" : ObjectId("58e559c76d3a9d2cb0449d85"),
        "CreatedOn" : ISODate("2017-04-05T20:21:23.234Z"),
        "Description" : "today"
}

更新:

"CreatedOn": ISODate("2017-03-31T20:27:12.914+05:00")

您的比较不起作用的原因是

 var start = new DateTime(2017, 03, 31);
 var end = new DateTime(2017, 03, 31);

这会$gte发送到服务器而不是ISODate("2017-03-31T00:00:00.000+05:00")$lte而不是ISODate("2017-03-31T00:00:00.000+05:00"),并且它找不到上述条目。

查询today日期的正确方法是

 var start = new DateTime(2017, 03, 31);
 var end = new DateTime(2017, 04, 01);

并将过滤器更新为

var filter = filterBuilder.Gte(x => x.CreatedOn, start) &
         filterBuilder.Lt(x => x.CreatedOn, end);

现在,您的范围查询作为$gte发送到服务器而不是ISODate("2017-03-31T00:00:00.000+05:00")$lt而不是ISODate("2017-04-01T00:00:00.000+05:00"),您应该能够找到今天的所有匹配项。

更新2

更改数据库以存储日期时间,时间部分设置为00:00:00。这也将从db中移除等式中的时间部分,并且您的旧范围查询将适用于所有情况。

更改保存方法以使用

var today = DateTime.Today; //2017-03-31 00:00:00.000

您可以返回旧的过滤器定义。

这样的东西
 var start = new DateTime(2017, 03, 31);
 var end = new DateTime(2017, 03, 31);

并将过滤器更新为

var filter = filterBuilder.Gte(x => x.CreatedOn, start) &
         filterBuilder.Lte(x => x.CreatedOn, end);

现在,您的范围查询作为$gte发送到服务器而不是ISODate("2017-03-31T00:00:00.000+05:00")$lte而不是ISODate("2017-03-31T00:00:00.000+05:00"),您应该能够找到今天的所有匹配项。

更新3 - 仅使用BsonDocument进行日期比较。

这里的想法是将+5:00的时区偏移添加到服务器的UTC日期,并使用yyyy-MM-dd运算符将计算的日期时间转换为字符串$dateToSting格式,然后进行比较输入字符串日期格式相同。

此功能适用于您的时区,但无法在夏令时中观察时区。

Mongo版本3.4

您可以使用$addFields阶段添加新字段CreatedOnDate,同时保留所有现有属性,并使用$project从比较后的最终答案中删除CreatedOnDate。< / p>

Shell Query:

{
    "$addFields": {
        "CreatedOnDate": {
            "$dateToString": {
                "format": "%Y-%m-%d",
                "date": {
                    "$add": ["$CreatedOn", 18000000]
                }
            }
        }
    }
}, {
    "$match": {
        "CreatedOnDate": {
            "$gte": "2017-03-31",
            "$lte": "2017-03-31"
        }
    }
}, {
    "$project": {
        "CreatedOnDate": 0
    }
}

C#代码:

var start = new DateTime(2017, 03, 31);
var end = new DateTime(2017, 03, 31);

var addFields = BsonDocument.Parse("{$addFields: { CreatedOnDate: { $dateToString: { format: '%Y-%m-%d', date: {$add: ['$CreatedOn', 18000000] }} }} }");

var match = new BsonDocument("CreatedOnDate", new BsonDocument("$gte", start.ToString("yyyy-MM-dd")).Add("$lte", end.ToString("yyyy-MM-dd")));

var project = new BsonDocument
     {
       { "CreatedOnDate", 0 }
     };

var pipeline = collection.Aggregate().AppendStage<BsonDocument>(addFields)
    .Match(match)
    .Project(project);

var list = pipeline.ToList();

List<Student> searchResult = list.Select(doc => BsonSerializer.Deserialize<Student>(doc)).ToList();

Mongo Version = 3.2

与上述相同,但此管道使用$project,因此您必须添加要在最终响应中保留的所有字段。

Shell Query:

{
    "$project": {
        "CreatedOn": 1,
        "Description": 1,
        "CreatedOnDate": {
            "$dateToString": {
                "format": "%Y-%m-%d",
                "date": {
                    "$add": ["$CreatedOn", 18000000]
                }
            }
        }
    }
}, {
    "$match": {
        "CreatedOnDate": {
            "$gte": "2017-03-31",
            "$lte": "2017-03-31"
        }
    }
}, {
    "$project": {
        "CreatedOn": 1,
        "Description": 1
    }
}

C#代码:

var start = new DateTime(2017, 03, 31);
var end = new DateTime(2017, 03, 31);

var project1 = new BsonDocument
    {
        { "CreatedOn", 1 },
        { "Description", 1 },
        { "CreatedOnDate", new BsonDocument("$dateToString", new BsonDocument("format", "%Y-%m-%d")
                            .Add("date", new BsonDocument("$add", new BsonArray(new object[] { "$CreatedOn", 5 * 60 * 60 * 1000 }))))
        }
    };

var match = new BsonDocument("CreatedOnDate", new BsonDocument("$gte", start.ToString("yyyy-MM-dd")).Add("$lte", end.ToString("yyyy-MM-dd")));

var project2 = new BsonDocument
    {
        { "CreatedOn", 1 },
        { "Description", 1 }
    };


var pipeline = collection.Aggregate()
.Project(project1)
.Match(match)
.Project(project2);

var list = pipeline.ToList();

List<Student> searchResult = list.Select(doc => BsonSerializer.Deserialize<Student>(doc)).ToList();

更新4 - 仅限日期比较,适用于日光节省。

Mongo Version = 3.6

所有内容保持不变,期望$dateToString将采用时区而非固定偏移量,这应考虑到日间保存更改。

Shell Update:

{
    "$addFields": {
        "CreatedOnDate": {
            "$dateToString": {
                "format": "%Y-%m-%d",
                "date": "$CreatedOn",
                "timezone": "America/New_York"
            }
        }
    }
}

C#更新:

var addFields = BsonDocument.Parse("{$addFields: { CreatedOnDate: { $dateToString: { format: '%Y-%m-%d', date: "$CreatedOn", "timezone": "America/New_York"} }} }");

答案 1 :(得分:0)

以下将显示您的POCO道具

    private DateTime _ShortDateOnly;
    [BsonElement("ShortDateOnly")]
    [BsonDateTimeOptions(DateOnly = true)]
    public DateTime ShortDateOnly {
        set { _ShortDateOnly = value; }
        get { return _ShortDateOnly.Date; }
    }

我用它来创建以下BSON文档

{{ 
    "_id" : CSUUID("12ce2538-2921-4da0-8211-9202da92d7f3"), 
    "first" : "Felipe", 
    "New" : "Ferreira", 
    "PublicPassword" : null, 
    "netWorth" : "20000.99", 
    "netWorth2" : 20000.990000000002, 
    "UserType" : "Admin", 
    "BirthDate" : ISODate("2019-06-22T18:59:01.861Z"), 
    "ShortDateOnly" : ISODate("2019-06-22T00:00:00Z") 
}}

请您将以下内容添加到您的POCO中,让我知道这是否足以满足您的要求?

答案 2 :(得分:0)

将Collection.Find()与过滤器一起使用。在您的“存储库模式”中或用于数据库查询的代码中,添加以下内容:

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>

#include <vector>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdlib>

cudaError_t convert_csv_file_monowave_numbers(std::vector<double>& bidPrice,    
    std::vector<double>& askPrice);

//1st kernel converts bid and ask price data to price direction data
__global__ void bid_ask_price_data_direction_data(const double *bidPrice, const double *askPrice, int *d_bidPrice_direction,int *d_askPrice_direction,int size)
{
    int tid = ((blockIdx.x * blockDim.x) + threadIdx.x)+1;  
    if(tid<=size)
    {
        //for bid prices
        bool ipred_bid = (bidPrice[tid] > bidPrice[tid-1]);
        bool ipred_bid2 = (bidPrice[tid] < bidPrice[tid-1]);
        bool ipred_bid3 = (bidPrice[tid] == bidPrice[tid-1]);
        if (ipred_bid) 
        {
            d_bidPrice_direction[tid]=1;//UP is 1 ,DOWN is 0,SIDEWAY IS 2
        }
        if (ipred_bid2) 
        {
            d_bidPrice_direction[tid]=0;//UP is 1 ,DOWN is 0,SIDEWAY IS 2       
        }
        if (ipred_bid3) 
        {
            d_bidPrice_direction[tid]=2;//UP is 1 ,DOWN is 0,SIDEWAY IS 2       
        }   
    
        //for ask prices
        bool ipred_ask = (askPrice[tid] > askPrice[tid-1]);
        bool ipred_ask2 = (askPrice[tid] < askPrice[tid-1]);
        bool ipred_ask3 = (askPrice[tid] == askPrice[tid-1]);
        if (ipred_ask) 
        {
            d_askPrice_direction[tid]=1;//UP is 1 ,DOWN is 0,SIDEWAY IS 2
        }
        if (ipred_ask2) 
        {
            d_askPrice_direction[tid]=0;//UP is 1 ,DOWN is 0,SIDEWAY IS 2       
        }
        if (ipred_ask3) 
        {
            d_askPrice_direction[tid]=2;//UP is 1 ,DOWN is 0,SIDEWAY IS 2       
        }
    }
    __syncthreads();
}

//2nd kernel converts bid and ask price direction data to number of ticks in each direction step_zero"step zero means that any direction with one tick is represented by 0 and direction with more than one tick has its first tick 0 then each tick is 1"
__device__ bool d_iteration=false;

__global__ void bid_ask_direction_data_num_ticks_step_zero(int *d_bidPrice_direction,int *d_askPrice_direction,int *d_bidPrice_num_ticks_step_0,int *d_askPrice_num_ticks_step_0)
{
    /////////////take care we did not make sideway condition yet////////////

    //the following line is to make sure that we start dealing with arrays from array[1] with tid=1 as tid-1=0 .Then we make specefic code for tid=0 
    int tid = ((blockIdx.x * blockDim.x) + threadIdx.x)+1;
    
    //the next line is used to record the status of iteration of the next code to calculate the number of ticks.this variable will be set by all threads then we use iteration_count to determine the number of times of iteration which is used in calculating number of ticks
    //d_iteration=false;
    
    //the following line is to make sure that we start with tid=1 as tid-1=0 .Then we make specefic code for tid=0 
    //if (tid!=0)
    //{
        //now convert up,down,sideway to number of ticks in each monowave
        bool ipred_bidPrice_direction_ticks = ((d_bidPrice_direction[tid] == d_bidPrice_direction[tid-1])|| (d_bidPrice_direction[tid]==2));//here we try to start manipulating sideway???????????????????????????????????????????
        if (ipred_bidPrice_direction_ticks) 
        {
            d_bidPrice_num_ticks_step_0[tid]=1;
            d_iteration=true;
        }
        if (!ipred_bidPrice_direction_ticks) 
        {
            d_bidPrice_num_ticks_step_0[tid]=0;
        }
        
        //now convert up,down,sideway to number of ticks in each monowave
        bool ipred_askPrice_direction_ticks = (d_askPrice_direction[tid] == d_askPrice_direction[tid-1]);
        if (ipred_askPrice_direction_ticks) 
        {
            d_askPrice_num_ticks_step_0[tid]=1;
            d_iteration=true;
        }
        if (!ipred_askPrice_direction_ticks) 
        {
            d_askPrice_num_ticks_step_0[tid]=0;
        }
        __syncthreads();
    //}
}

//3rd kernel converts bid and ask number of ticks in each direction step_zero"step zero means that any direction with one tick is represented by 0 and direction with more than one tick has its first tick 0 then each tick is 1"
__device__ int d_iteration_count=0;
__global__ void bid_ask_num_ticks_step_zero_further_steps(int *d_bidPrice_num_ticks_step_0, int *d_askPrice_num_ticks_step_0, int *d_intermediate)
{
    int tid = ((blockIdx.x * blockDim.x) + threadIdx.x)+1;

    //bool ipred_bidPrice_num_ticks_step_0 = d_bidPrice_num_ticks_step_0[tid];
    if (d_bidPrice_num_ticks_step_0[tid] == 0) 
    {
        d_intermediate[tid]=0;
        //d_iteration=true;
    }
    else if (d_bidPrice_num_ticks_step_0[tid] != 0) 
    {
        if ((d_bidPrice_num_ticks_step_0[tid] == 1) && (d_bidPrice_num_ticks_step_0[tid-1] == 0)) 
        {
            d_intermediate[tid]=1;
            //d_iteration=true;
        }
        else if (d_bidPrice_num_ticks_step_0[tid] == d_bidPrice_num_ticks_step_0[tid-1]) 
        {
            d_intermediate[tid]=((d_bidPrice_num_ticks_step_0[tid-1] + d_bidPrice_num_ticks_step_0[tid])-(d_iteration_count - 1));
        }
    }
    __syncthreads();

    //bool ipred_askPrice_num_ticks_step_0 = d_askPrice_num_ticks_step_0[tid];
    if (d_askPrice_num_ticks_step_0[tid] == 0) 
    {
        d_intermediate[tid]=0;
        //d_iteration=true;
    }
    else if (d_askPrice_num_ticks_step_0[tid] != 0) 
    {
        if ((d_askPrice_num_ticks_step_0[tid] == 1) && (d_askPrice_num_ticks_step_0[tid-1] == 0)) 
        {
            d_intermediate[tid]=1;
            //d_iteration=true;
        }
        else if (d_askPrice_num_ticks_step_0[tid] == d_askPrice_num_ticks_step_0[tid-1]) 
        {

            d_intermediate[tid]=((d_askPrice_num_ticks_step_0[tid-1] + d_askPrice_num_ticks_step_0[tid])-(d_iteration_count - 1));
        }
    }
    __syncthreads();
}

int main()
{  
    //FIRST we get the data from csv file to work with it
    std::string path ="GBPJPY_2020_08_30_.csv";
    std::ifstream data(path);
    std::string line;

    // Declare data storage  
    std::vector<long long> tickTime;
    std::vector<double> bidPrice;
    std::vector<double> askPrice;
    std::vector<double> bidVolume;
    std::vector<double> askVolume;
    
    int lineCounter={0};
    while(std::getline(data,line))
    {
        int cellCounter={0};

        std::stringstream lineStream(line);
        std::string cell;
                
        while(std::getline(lineStream,cell,','))
        {            
            switch (cellCounter)  
            {
                case 0:
                    // code to be executed if
                    // expression is equal to constant1;
                    //tickTime.push_back(::atof(cell.c_str());std::stod(s);
                    tickTime.push_back(std::stoll(cell));

                    break;
                case 1:
                    // code to be executed if
                    // expression is equal to constant1;
                    //tickTime.push_back(::atof(cell.c_str());std::stod(s);
                    //tickTime.push_back(std::stod(cell));

                    break;
                case 2:
                    // code to be executed if
                    // expression is equal to constant2;
                    //bidPrice.push_back(::atof(cell.c_str());
                    bidPrice.push_back(std::stod(cell));

                    break;

                case 3:
                    // code to be executed if
                    // expression is equal to constant1;
                    //askPrice.push_back(::atof(cell.c_str());
                    bidVolume.push_back(std::stod(cell));


                    break;

                case 4:
                    // code to be executed if
                    // expression is equal to constant2;
                    //bidVolume.push_back(::atof(cell.c_str());
                    askPrice.push_back(std::stod(cell));

                    break;
                case 5:
                    // code to be executed if
                    // expression is equal to constant2;
                    //askVolume.push_back(::atof(cell.c_str());
                    askVolume.push_back(std::stod(cell));

                    break;
                default:
                    // code to be executed if
                    // expression doesn't match any constant
                    throw;
            }

            //increment cellCounter at end so first element is 0 not 1
            ++cellCounter;
        }       
        ++lineCounter;
    }
    
    //SECOND start the helper function which is the main target of this program
    // convert csv file to monowave file.
    cudaError_t cudaStatus = convert_csv_file_monowave_numbers(//tickTime,
        bidPrice,// bidVolume,
        askPrice//,askVolume);
        );
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "convert_csv_file_monowave_numbers failed!");
        return 1;
    }

    //THIRD calculate monowaves serially on CPU

    
    // cudaDeviceReset must be called before exiting in order for profiling and
    // tracing tools such as Nsight and Visual Profiler to show complete traces.
    cudaStatus = cudaDeviceReset();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceReset failed!");
        return 1;
    }

    return 0;
}

// Helper function for using CUDA to add vectors in parallel.
cudaError_t convert_csv_file_monowave_numbers(std::vector<double>& bidPrice,    
    std::vector<double>& askPrice)
{
    //these pointers are used to store csv data on gpu   
    double *d_bidPrice=0;   
    double *d_askPrice=0;    
    
    //these pointers are used to store results of converting csv data to monowave requirements      
    int *d_bidPrice_direction=0;   
    int *d_askPrice_direction=0;
    int *d_bidPrice_num_ticks_step_0=0;   
    int *d_askPrice_num_ticks_step_0=0; 
    
    int *d_intermediate_1=0;    
    int *d_intermediate_2=0; 
    cudaError_t cudaStatus;

    //these pointers will be used to test output
    int *h_bidPrice_direction=0;   
    int *h_askPrice_direction=0;
    int *h_bidPrice_num_ticks_step_0=0;   
    int *h_askPrice_num_ticks_step_0=0;

    // Choose which GPU to run on, change this on a multi-GPU system.
    cudaStatus = cudaSetDevice(0);
    if (cudaStatus != cudaSuccess) 
    {
        fprintf(stderr, "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?");
        goto Error;
    }

    // Allocate GPU buffers for two vectors (two inputs)    .
    
    cudaStatus = cudaMalloc((void**)&d_bidPrice, bidPrice.size()*sizeof(double));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&d_askPrice, askPrice.size()*sizeof(double));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }
    

    // Allocate GPU buffers for four resulting arrays (four output)    .
    
    cudaStatus = cudaMalloc((void**)&d_bidPrice_direction, bidPrice.size()*sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&d_askPrice_direction, askPrice.size()*sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&d_bidPrice_num_ticks_step_0, bidPrice.size()*sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&d_askPrice_num_ticks_step_0, askPrice.size()*sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }
    

    // Allocate GPU buffers for two intra kernel iteration storing arrays (two intermediate buffers )    .
    cudaStatus = cudaMalloc((void**)&d_intermediate_1, bidPrice.size()*sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&d_intermediate_2, bidPrice.size()*sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    // Copy input vectors from host memory to GPU buffers.  
    cudaStatus = cudaMemcpy(d_bidPrice, bidPrice.data(), bidPrice.size()*sizeof(double), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    cudaStatus = cudaMemcpy(d_askPrice, askPrice.data(), askPrice.size()*sizeof(double), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }   
    
    // set up data size
    int size = bidPrice.size();
    int blocksize = 32;
    // set up execution configuration
    dim3 block (blocksize,1);
    dim3 grid ((size+block.x-1)/block.x,1);
    printf("Execution Configure (block %d grid %d)\n",block.x, grid.x);
        
    //launch first kernel
    bid_ask_price_data_direction_data<<<grid, block>>>(bidPrice.data(),askPrice.data() , d_bidPrice_direction,d_askPrice_direction,size);
    ////////////////////////////////////////////////////////////////////////////
    // Check for any errors launching the kernel
    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "bid_ask_price_data_direction_data launch failed: %s\n", cudaGetErrorString(cudaStatus));
        goto Error;
    }
    
    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cudaStatus = cudaDeviceSynchronize();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching bid_ask_price_data_direction_data!\n", cudaStatus);
        goto Error;
    }   

    // Copy output vector from GPU buffer to host memory.   
    cudaStatus = cudaMemcpy(h_bidPrice_direction, d_bidPrice_direction, bidPrice.size() * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }
    cudaStatus = cudaMemcpy(h_askPrice_direction, d_askPrice_direction, askPrice.size() * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    //show the bid and ask prices and Price_direction
    for(int i=0;i < askPrice.size();i++)
    {
        std::cout << bidPrice.data()[i] <<h_bidPrice_direction[i] << askPrice.data()[i] << h_askPrice_direction[i] << std::endl;
    }
    
    //launch 2nd kernel
    bid_ask_direction_data_num_ticks_step_zero<<<grid, block>>>(d_bidPrice_direction,d_askPrice_direction,d_bidPrice_num_ticks_step_0,d_askPrice_num_ticks_step_0);
    ////////////////////////////////////////////////////////////////////////////
    // Check for any errors launching the kernel
    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "bid_ask_direction_data_num_ticks_step_zero launch failed: %s\n", cudaGetErrorString(cudaStatus));
        goto Error;
    }
    
    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cudaStatus = cudaDeviceSynchronize();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching bid_ask_direction_data_num_ticks_step_zero!\n", cudaStatus);
        goto Error;
    }
    /////////////////////////////////////////////////////////////////////////////
    
    // Copy output vector from GPU buffer to host memory.    
    cudaStatus = cudaMemcpy(h_bidPrice_num_ticks_step_0, d_bidPrice_num_ticks_step_0, bidPrice.size() * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }
    cudaStatus = cudaMemcpy(h_askPrice_num_ticks_step_0, h_askPrice_num_ticks_step_0, askPrice.size() * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }
    
    //prepare for 3rd kernel
    bool h_iteration=false;
    int h_iteration_count=0;
    cudaStatus = cudaMemcpyFromSymbol(&h_iteration, "d_iteration", sizeof(h_iteration), 0, cudaMemcpyDeviceToHost);
     if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpyFromSymbol failed!");
        goto Error;
    }
    printf("iteration: %d\n", h_iteration);
    
    //determine from value of h_iteration if we will make loop which launch kernel to convert bid and ask number of ticks_step_0 to further steps to calculate total number of ticks in each monowave
    if(h_iteration)
    {
        //this indicate that iteration is true and we need to start kernel to convert step_0 to further steps
        //h_iteration_count++;
        while(h_iteration)
        {
            h_iteration_count++;

            //launch 3rd kernel
            cudaMemcpyFromSymbol(&d_iteration_count, "h_iteration_count", sizeof(h_iteration_count), 0, cudaMemcpyHostToDevice);
            //we need to determine if iteration count is odd or even, to determine which d_intermediate will be used
            if(h_iteration_count % 2 !=0)
            {
                //iteration count is odd. So we use d_intermediate_1 

            }
            else if(h_iteration_count % 2 ==0)
            {
                //iteration count is even. So we use d_intermediate_2

            }
        }

    }
    else if(!h_iteration)
    {

    }
    ////////////////////////////////////////////////////////////////////////////
    // Check for any errors launching the kernel
    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "bid_ask_price_data_direction_data launch failed: %s\n", cudaGetErrorString(cudaStatus));
        goto Error;
    }
    
    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cudaStatus = cudaDeviceSynchronize();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching bid_ask_price_data_direction_data!\n", cudaStatus);
        goto Error;
    }
    /////////////////////////////////////////////////////////////////////////////
    /*
    // Copy output vector from GPU buffer to host memory.
    cudaStatus = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }
    */
    /////////////////////////////////////////////////////////////////////////////
Error:
    
    cudaFree(d_bidPrice);
    cudaFree(d_askPrice);
   
    cudaFree(d_bidPrice_direction);
    cudaFree(d_askPrice_direction);
    
    cudaFree(d_bidPrice_num_ticks_step_0);
    cudaFree(d_askPrice_num_ticks_step_0);

    cudaFree(d_intermediate_1);
    cudaFree(d_intermediate_2);


    cudaDeviceReset();

    return cudaStatus;
}

并这样称呼:

   public async Task<List<T>> FindAll(Expression<Func<T, bool>> filter)
{


    try
    {
        //Fetch the filtered list from the Collection
        List<T> documents = await Collection.Find(filter).ToListAsync();


        //return the list
        return documents;

    }
    catch (Exception ex)
    {
        return await Task.FromResult(new List<T>() { });
    }

}

_someClass应该绝对由包含FindAll函数的类的实例替换

答案 3 :(得分:-1)

使用时

new DateTime(2017, 03, 31);

你得到一个DateTime对象,这意味着它也会计算时间。 因此,通过对开始和停止使用相同的解析,您实际上得到的内容等于:

var start = var end = new DateTime("31/03/2017 00:00:00.00");

当然,您可能在此特定时间范围内没有任何记录。 如果你真的想要获得今天的所有记录,你应该这样做:

var start = new DateTime("31/03/2017 00:00:00.00");
var end =   new DateTime("31/03/2017 23:59:59.99");