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

MongoDB使用BsonDocument筛选多值匹配数据时遇重复元素错误

解决MongoDB BsonDocument查询重复键报错问题

你遇到的Duplicate element name '$eq'错误,是因为嵌套的BsonDocument里重复使用了$eq作为键——BsonDocument不允许存在重复键名,而且$eq本身只能匹配单个值,没法通过多次添加实现“或”的筛选逻辑。

要实现“name字段等于数组中任一值”的查询,应该用MongoDB的$in操作符,它专门用来匹配字段值在指定数组范围内的文档。正确的BsonDocument写法如下:

query = new BsonDocument
{
    {"name", new BsonDocument("$in", new BsonArray {"bill", "fred"})}
};

var entities = await collection.Find(query).ToListAsync();

如果你的项目里用了MongoDB的强类型构建器,还可以用更简洁、可读性更高的写法:

// 假设你的实体类型是YourEntity,对应name字段的属性是Name
var filter = Builders<YourEntity>.Filter.In(x => x.Name, new string[] {"bill", "fred"});
var entities = await collection.Find(filter).ToListAsync();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:20:03