You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C# BsonDocument匹配含指定字符串的MongoDB数组文档

MongoDB数组包含指定字符串的C# BsonDocument查询实现

方案1:使用ElemMatch运算符

针对需求,可通过正则表达式结合ElemMatch匹配数组中包含foo的元素,代码实现如下:

var docFilter = Builders<BsonDocument>.Filter;
var valueFilter = Builders<BsonValue>.Filter;
// 构建匹配条件:messages数组中存在包含foo的字符串
var findFilter = docFilter.ElemMatch<BsonValue>("messages", valueFilter.Regex(new BsonRegularExpression("foo")));
var result = await collection.FindAsync(findFilter);

如果需要不区分大小写匹配,可修改正则表达式为new BsonRegularExpression("foo", "i")。

方案2:更简洁的直接正则匹配(推荐)

对于单条件的数组元素匹配,无需使用ElemMatch,直接对数组字段应用正则查询即可,代码更简洁:

var filter = Builders<BsonDocument>.Filter.Regex("messages", new BsonRegularExpression("foo"));
var result = await collection.FindAsync(filter);

效果说明

两种方案都会返回_id为1的文档,因为该文档的messages数组中存在包含foo的字符串,_id为2的文档会被过滤掉。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:43:11