C#中MongoDB聚合查询如何传递原生new Date()函数
解决MongoDB视图聚合管道中动态当前日期的构造问题
你需要在聚合管道的$match阶段生成动态的当前日期条件,而非固定日期或带引号的字符串/Code类型,以下是两种可行方案:
方案1:使用官方聚合日期操作符(推荐)
MongoDB 4.0及以上版本支持$dateNow操作符,可直接在聚合管道中获取当前日期,性能优于JavaScript表达式,且符合BSON标准。C#代码构造方式如下:
var pipeline = new List<BsonDocument> { new BsonDocument("$match", new BsonDocument("$expr", new BsonDocument("$and", new BsonArray { new BsonDocument("$lte", new BsonArray { "$create", new BsonDocument("$dateNow", new BsonDocument()) }), new BsonDocument("$gte", new BsonArray { "$end", new BsonDocument("$dateNow", new BsonDocument()) }) }))) // 其他管道阶段... };
生成的聚合管道为:
{ "$match": { "$expr": { "$and": [ { "$lte": ["$create", { "$dateNow": {} }] }, { "$gte": ["$end", { "$dateNow": {} }] } ] } } }
该方式会在每次查询视图时自动计算当前日期,完全满足需求。
方案2:生成new Date()语法(不推荐,仅兼容旧版本)
如果必须使用new Date()语法,需借助BsonJavaScript并结合$where(注意:$where会触发全表扫描,性能极差,仅建议在旧版本MongoDB中临时使用):
var pipeline = new List<BsonDocument> { new BsonDocument("$match", new BsonDocument("$where", new BsonJavaScript( "this.create <= new Date() && this.end >= new Date()" ))) // 其他管道阶段... };
之前尝试失败的原因
你之前用new BsonDocument("new Date()")的方式完全错误,会生成空的嵌套文档而非日期表达式;BsonString会把new Date()转为字符串,BsonJavaScript会被序列化为Code类型,只有结合$where才能让MongoDB执行该JavaScript表达式。
内容的提问来源于stack exchange,提问作者IchLiebeKadarka
相关产品推荐
相关产品推荐

