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

MongoDB C#客户端如何实现字段值为字符串或数字的查询?

解决MongoDB中匹配不同类型字段值的查询问题

要查询age字段为数字65或字符串"65"的文档,不能重复使用$eq键(MongoDB会覆盖重复键导致无效),正确的做法是使用**$in**操作符,将两种不同类型的目标值放入数组,一次性匹配两种情况。

正确的MongoDB查询语句

{ age: { $in: [65, "65"] } }

C#实现方案

方案1:使用MongoDB.Driver的FilterDefinitionBuilder(推荐,类型安全)

借助官方驱动的过滤器构建器,更简洁且不易出错:

using MongoDB.Driver;

// 针对无实体类的BsonDocument集合构建过滤器
var filter = Builders<BsonDocument>.Filter.In("age", new BsonValue[] { 65, "65" });

// 如果有对应实体类(比如Person),可通过属性名构建:
// var filter = Builders<Person>.Filter.In(p => p.Age, new BsonValue[] { 65, "65" });

// 执行查询
var matchedDocs = collection.Find(filter).ToList();

方案2:手动构建BsonDocument(适配原有代码逻辑)

如果你需要手动拼接查询文档,修改原有代码为以下形式,避免重复键问题:

var para = comparisonOperator.Parameter.Name;
var value = comparisonOperator.Value.Name;
BsonDocument filterDocument = new BsonDocument();

if (int.TryParse(value, out int intValue))
{
    // 构建包含数字和字符串的$in数组
    var inValues = new BsonArray { intValue, value };
    filterDocument.Add(para, new BsonDocument("$in", inValues));
}
else
{
    // 无法解析为数字时,仅匹配字符串值
    filterDocument.Add(para, new BsonDocument("$eq", value));
}

这个逻辑通过$in操作符替代重复的$eq键,同时覆盖了数字和字符串两种类型的匹配需求,不会出现重复键报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:50:28