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

MongoDB集合数组中通过IdS3查询单个对象的C#实现

在C#中查询MongoDB数组中匹配IdS3的单个对象的实现思路

方法1:使用聚合管道(推荐,精准控制输出)

通过聚合管道可以精准过滤并提取数组中匹配的单个对象,步骤清晰可控:

  1. $match:先定位包含目标IdS3的父文档,缩小查询范围
  2. $unwind:展开StoredDocuments数组,将每个数组元素转为独立文档
  3. $match:再次筛选出IdS3匹配的文档
  4. $replaceRoot:将匹配的数组对象设为根文档,直接返回该对象

C#代码示例:

var targetIdS3 = 12345; // 替换为你要查询的IdS3值
var collection = mongoDatabase.GetCollection<BsonDocument>("你的集合名称");

var pipeline = new BsonDocument[]
{
    new BsonDocument("$match", new BsonDocument("StoredDocuments.IdS3", targetIdS3)),
    new BsonDocument("$unwind", "$StoredDocuments"),
    new BsonDocument("$match", new BsonDocument("StoredDocuments.IdS3", targetIdS3)),
    new BsonDocument("$replaceRoot", new BsonDocument("newRoot", "$StoredDocuments"))
};

var result = await collection.Aggregate<BsonDocument>(pipeline).FirstOrDefaultAsync();
// 若有对应的实体类,可替换BsonDocument为你的实体类型

方法2:使用投影过滤数组

通过投影操作中的$filter操作符,直接在父文档中过滤出匹配的数组元素,再提取单个对象:

C#代码示例:

var targetIdS3 = 12345;
var collection = mongoDatabase.GetCollection<YourParentEntity>("你的集合名称");

var projection = Builders<YourParentEntity>.Projection
    .Include(x => x.StoredDocuments)
    .ElemMatch(x => x.StoredDocuments, d => d.IdS3 == targetIdS3);

var parentDoc = await collection.Find(x => x.StoredDocuments.Any(d => d.IdS3 == targetIdS3))
    .Project(projection)
    .FirstOrDefaultAsync();

// 提取匹配的单个数组对象
var matchedDoc = parentDoc?.StoredDocuments?.FirstOrDefault();

方法3:使用LINQ SelectMany展开查询

利用LINQ的SelectMany直接展开数组并过滤,一步得到匹配的对象:

C#代码示例:

var targetIdS3 = 12345;
var collection = mongoDatabase.GetCollection<YourParentEntity>("你的集合名称");

var matchedDoc = await collection.AsQueryable()
    .SelectMany(parent => parent.StoredDocuments)
    .Where(doc => doc.IdS3 == targetIdS3)
    .FirstOrDefaultAsync();

注意事项:

  • 建议给StoredDocuments.IdS3字段创建索引,提升查询性能
  • 使用实体类时,确保属性与MongoDB字段映射正确(可通过BsonElement特性配置)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:27:17