简体   繁体   中英

Is there a way to convert mongoDB json query to mongodb driver

I am new to mongoDB and currently working on already created application. The project is in .net core and uses MongoDb driver to interact with mongo. Since I am unfamiliar with mongo, the client has provided query to fetch data, but I am not able to convert it into mongoDB driver code in C#.

Can anyone help me out on it. This is the query provided:

 db['customer'].aggregate([
{
    '$match': {
        '$and': [
            {'Date': {'$gt': ISODate('2020-07-01T00:00:00.000Z'), '$lt': ISODate('2020-08-24T00:00:00.000Z')}},
        ]
    }
},
{
    '$project': {
        'domain': {$arrayElemAt: [{'$split':['$Referer','/']},2]},
        'referer': '$Referer'
    }
},
{
    '$group': {
        '_id': {'domain': '$domain'},
        'count': {'$sum':1}
    },
},
{
    '$sort':{'count':-1}
}

])

Any help would be really appreciated.

Thanks

You can use the fluent aggregation api within the C# driver to build up the aggregation pipeline, this has some slight downsides as some things are not supported in a type-safe way such as the arrayElemAt , but we can just use a BsonDocument to represent this.

var client = new MongoClient();
var db = client.GetDatabase("test");
var customers = db.GetCollection<Customer>("customer");

var dateGreaterThan = DateTime.UtcNow.AddDays(-1);
var dateLessThan = DateTime.UtcNow.AddDays(1);

var results = await customers.Aggregate()
    .Match(
        Builders<Customer>.Filter.Gt(x => x.Date, dateGreaterThan)
        & Builders<Customer>.Filter.Lt(x => x.Date, dateLessThan)
    )
    .Project<CustomerProjection>(
        Builders <Customer>.Projection.Combine(
            Builders<Customer>.Projection.Include(x => x.Referer),
            BsonDocument.Parse(@"{ ""Domain"": { $arrayElemAt: [ { ""$split"": [ ""$Referer"", ""/"" ] }, 2 ] } }")
        ))
    .Group(projection => projection.Domain, grouping => new {Id = grouping.Key, Count = grouping.Count()})
    .SortByDescending(document => document.Count)
    .ToListAsync();
public class Customer
{
    public ObjectId Id { get; set; }

    public DateTime Date { get; set; }

    public string Referer { get; set; }
}

public class CustomerProjection
{
    public string Referer { get; set; }

    public string Domain { get; set; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM