我开始在我的应用程序中使用 MongoDB。我正在使用 Robo 3T 来学习和测试查询,现在,我正在将查询转换为 C#。我对 MONGO ROBO 3T 的疑问db.dbCENTRAL.aggregate([ { $match: { PartnerId: "2021", DATAINST: {$gte: "2018-01-01 00:00:00", $lte: "2019-03-12 23:59:59"}, } }, { $group: { _id: { $substr : ["$DATAINST", 0, 10 ] }, count: { $sum: 1 }} }])在 Robo 3T 上运行上面的脚本,它检索到了这个结果:{ "_id" : "2018-01-10", "count" : 1.0}/* 2 */{ "_id" : "2018-02-09", "count" : 1.0}/* 3 */{ "_id" : "2018-02-26", "count" : 1.0}/* 4 */{ "_id" : "2018-03-02", "count" : 1.0}/* 5 */{ "_id" : "2018-03-08", "count" : 1.0}现在,我试图在我的 .NET MVC 项目上重现这个结果,但我很难将子字符串转换为 C#。C# 代码var connString = "mongodb+srv:";var client = new MongoClient(connString);var db = client.GetDatabase("SyncMaster");var collection = db.GetCollection<BsonDocument>("dbCENTRAL");var match1 = new BsonDocument("$match", new BsonDocument("PartnerId", "2021"));var match2 = new BsonDocument { { "$match", new BsonDocument { { "DATAINST", new BsonDocument { { "$gte", data1 }, { "$lt", data2 } } } } } };var group = new BsonDocument { { "$group", new BsonDocument { { "_id", new BsonDocument { { "Dia", "$DATAINST" } } }, { { { "$sum", 1 } } } } } };
1 回答
MYYA
TA贡献1868条经验 获得超4个赞
您是否尝试过仅使用流利的 C# 语法来创建聚合管道?
var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<Central>("dbCENTRAL");
var filter = Builders<Central>.Filter.Eq(x => x.PartnerId, "2021")
& Builders<Central>.Filter.Gte(x => x.DATAINST, "2018-01-01 00:00:00")
& Builders<Central>.Filter.Lte(x => x.DATAINST, "2019-03-12 23:59:59");
var listAsync = await collection.Aggregate()
.Match(filter)
.Group(central => central.DATAINST.Substring(0, 10), g => new { Id = g.Key, Count = g.Count()})
.ToListAsync();
- 1 回答
- 0 关注
- 100 浏览
添加回答
举报
0/150
提交
取消