c#驱动程序和shell产生不同的结果



我有两个集合;ProductStemCollections ProductStems。

public abstract class Document : IDocument
{
[BsonId]
[BsonRepresentation( BsonType.String )]
public ObjectId Id { get; set; }
}
[BsonCollection( "ProductStemCollections" )]
public class ProductStemCollection : Document
{
public string Name { get; set; }
[BsonRepresentation( BsonType.String )]
public List<ObjectId> ProductStems { get; set; } = new List<ObjectId>();
}
[BsonCollection( "ProductStems" )]
public class ProductStem : Document
{
[BsonRepresentation(BsonType.String)]
public ObjectId PromotedProductId { get; set; }
public string ProductCode { get; set; }
}

我想聚合在一个茎集合中列出的茎,像这样:

var query = prodStemCollectionRepo.Collection
.Aggregate()
.Lookup( "ProductStems", "ProductStems", "_id", "stems" );
var strQuery = query.ToString();
var results = await query.ToListAsync();

这将产生查询

db.ProductStemCollections.aggregate([{ "$lookup" : { "from" : "ProductStems", "localField" : "ProductStems", "foreignField" : "_id", "as" : "stems" } }])

如果我在Cosmos db shell中运行这个查询,我得到了想要的结果:

{
"_id" : "61694434ba77dc8362d56858",
"Name" : "Sweden",
"ProductStems" : [
"61694434ba77dc8362d56859",
"61694434ba77dc8362d5685b",
"61694435ba77dc8362d5685d",
"61694435ba77dc8362d5685f",
"61694436ba77dc8362d56861",
"61694438ba77dc8362d56863"
],
"stems" : [
{
"_id" : "61694434ba77dc8362d56859",
"PromotedProductId" : "61694434ba77dc8362d5685a",
"ProductCode" : "P1"
}
...
]
}

然而,运行上面的c#代码不会产生相同的结果,即使查询是相同的数组"stems"缺失:

{
{
"_id": "61694434ba77dc8362d56858",
"Name": "Sweden",
"ProductStems": [
"61694434ba77dc8362d56859",
"61694434ba77dc8362d5685b",
"61694435ba77dc8362d5685d",
"61694435ba77dc8362d5685f",
"61694436ba77dc8362d56861",
"61694438ba77dc8362d56863"
]
}
}

我错过了什么?

好的,所以我最终选择了Mongo Db Atlas。创建了一个聚合类,该类包含一个带有其茎的茎集合:

public class AggregatedStemCollection : Document
{
public string? Name { get; set; }

[BsonRepresentation(BsonType.String)]
public List<ObjectId> ProductStems { get; set; } = new List<ObjectId>();
public List<ProductStem> Stems { get; set; } = new List<ProductStem>();
}

并修改了lind查询:

var query = prodStemCollectionRepo.Collection
.Aggregate()
.Match( c => c.Name == "Sweden" )
.Lookup(
foreignCollection: productStemRepo.Collection,
localField: x => x.ProductStems,
foreignField: y => y.Id,
@as: ( AggregatedStemCollection asc ) => asc.Stems );
var results = query.ToList();

相关内容