I need to convert ISODate to string format like "2019-06-27" this, and also need to apply a sort on it by date. However, I've converted date in required format but messing up with date sort due to date string format which is earlier converted.
App Environment
- .NET MongoDB Driver - 2.0
- MongoDB version - 3.2
This is how the document stored in the MongoDB collection:
{
"_id": "9d78d0e8-7b13-4487-88a3-d91d64f29b38",
"Number": "001",
.......,
.......,
"createdon": {
"$date": "2019-09-19T00:00:00.000Z"
},
"modifiedon": {
"$date": "2019-12-17T19:52:00.000Z"
}
}
And this is the working C# function but without date sort:
public string GetData(Data.DataModel.TestModel model)
{
string collectionName = "testCollection";
BsonDocument sort = new BsonDocument();
BsonDocument match = new BsonDocument();
BsonDocument project = new BsonDocument();
int skip = model.skip;
int limit = model.limit;
try
{
match.Add();
project.AddRange(new BsonDocument {
{ "TDLNumber", 1 },
{ "createdon", new BsonDocument("$dateToString",
new BsonDocument("format", "%Y-%m-%d").Add("date", "$createdon")) // format like 2019-06-27
},
{ "modifiedon", new BsonDocument("$dateToString",
new BsonDocument("format", "%Y-%m-%d").Add("date", "$modifiedon"))// format like 2019-06-27
}
});
sort.AddRange(new BsonDocument { { "createdon", -1 }, { "modifiedon", -1 } });
List<BsonDocument> lstReslut = dbo.FindAggDynQuery(collectionName, match, project, skip, limit, sort);
QueryResult = lstReslut.ToJson();
}
catch (Exception)
{
QueryResult = "[]";
}
return QueryResult;
}
But if I do without date convert it works perfectly like this
{ "createdon", 1},
{ "modifiedon",1},
// { "createdon", new BsonDocument("$dateToString",
// new BsonDocument("format", "%Y-%m-%d").Add("date", "$createdon")) // format like 2019-06-27
// },
//{ "modifiedon", new BsonDocument("$dateToString",
// new BsonDocument("format", "%Y-%m-%d").Add("date", "$modifiedon"))// format like 2019-06-27
//}
Here's databae layer query function:
public List<BsonDocument> FindAggDynQuery(string collectionName, BsonDocument find, BsonDocument project, int skip, int limit, BsonDocument sort)
{
using (var connectionManager = new Test.Data.ConnectionManager())
{
var _collection = connectionManager.GetDBCollection(collectionName);
var result = _collection.Find(find).Sort(sort).Project(project).Skip(skip).Limit(limit).ToListAsync().Result;
return result;
}
}
What's going wrong here. Any help would be appreciate!!
descendant, while before converting into string, you are sortingascending. Is It correct? Other thing: why you don't Sort dates being Date where mongodb can use indexes and then with$projectyou convert them?aggregate. Take a look stackoverflow.com/a/36407426/3710490