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

MongoDB C#驱动投影操作中ObjectId序列化异常求助

问题分析与解决方案

错误根源

你在Projection中错误地将Builders<Child>.Filter.In作为Include的参数,Include方法仅用于指定需要返回的字段,无法解析过滤表达式,这直接导致了序列化异常。你的需求是筛选出指定Parent下ChildId匹配给定数组的子文档,需要用**数组过滤操作符$filter**来实现,而非错误地在Include中嵌入过滤逻辑。

正确实现代码

以下是修正后的聚合查询代码,通过$filter筛选子数组:

string parentId = "638a4259e431d53971444ba4";
string[] childIds = new string[] { "638d1b92c50872c01df4a8fb", "6398dc29ca4933fb1e4f0644" };

var findParentFilter = Builders<Parent>.Filter.Eq(x => x.ParentId, parentId);

// 使用$filter操作符过滤Childs数组
var projection = Builders<Parent>.Projection
    .Expression(p => new Parent
    {
        ParentId = p.ParentId,
        Title = p.Title,
        Description = p.Description,
        Childs = p.Childs.Where(c => childIds.Contains(c.ChildId)).ToList()
    });

var result = quizCollection.Aggregate()
    .Match(findParentFilter)
    .Project<Parent>(projection)
    .FirstOrDefault();

补充说明

  • 由于你的实体类已经通过[BsonRepresentation(BsonType.ObjectId)]将字符串映射为ObjectId,驱动会自动处理字符串与ObjectId的转换,无需手动将childIds数组转换为ObjectId类型。
  • 如果只需要返回过滤后的子文档和父文档ID,可简化Projection中的字段,只保留必要的部分。
  • 若数据量较大,也可以考虑在聚合中使用$unwind+$match+$group的组合来实现,但对于单文档内的数组过滤,$filter是更高效的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:27:12