I have the following query in mongoDB
pdb.getCollection('articulo').aggregate(
{
$match: { $text: { $search: "monitor" } } ,
},
{
$project: {
_id: 1,
titulo :1,
ranking : {
$avg: "$valoracion.valor"
}
}
},
{
$sort : {
ranking : -1 , fechaAlta : -1
}
});
And I'm trying to convert it to a C # query (MongoDB.Driver), but I have a problem with the calculated field (average) in the projection.
My question is:
How can I get a calculated field ("ranking") in the projection?
This is what I have:
public async Task<List<T>> All<T>(string searchBy, int page, int size) where T : class, new()
{
try
{
var projectionSelect = Builders<T>.Projection.Include("_id")
.Include("titulo")
//.Include(new BsonDocument { { "rating", new BsonDocument { { "$avg", "$valoracion.valor" } } } }); that didn´t wokt for me
return await _dataBase.GetCollection<T>(GetName<T>()).Aggregate().Project<T>(projectionSelect)
.Sort(Builders<T>.Sort.Descending("ranking")).Skip(page).Limit(size).ToListAsync();
}
catch (Exception ex)
{
Log.Instance.LogErrors(ex);
throw;
}
}
I appreciate the help in advance
Copyright Notice:Content Author:「M. Saponara」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/42769971/calculate-field-in-a-projection-mongodb-c-sharp