db.sectors.aggregate([
{
"$lookup": {
"from": "virtualChains",
"localField": "VirtualChainId",
"foreignField": "_id",
"as": "VirtualChains"
}
},
{
"$unwind": "$VirtualChains"
},
{
"$unwind": "$VirtualChains.ZoneConfigInfos"
},
{
"$match": {
"VirtualChains.ZoneConfigInfos.ZoneId": ObjectId("ZoneId")
}
},
{
"$project": {
"_id": 1,
"Name": 1,
"ArabicName": 1,
"Code": 1,
"ImageUrl": 1,
"ArabicImageUrl": 1,
"Index": 1,
"Description": 1,
"DescriptionAR": 1,
"IsVirtual": 1,
"StoreId": "$VirtualChains.ZoneConfigInfos.StoreId"
}
}
])
上面的 Mongo 查询运行良好并返回值。但在 C# 代码中它会返回如下错误。
如果我添加以下代码,它将返回为:
JSON 读取器期望一个值,但发现了“VirtualChains”。
var virProjectDoc = Utils.GetProjectQuery(Properties.Resources.VIRTUAL_SECTOR_PROJECT);
var virSecBuilder = Builders<BsonDocument>.Filter;
var virFilter = virSecBuilder.AnyEq("VirtualChains.ZoneConfigInfos.ZoneId", ObjectId.Parse(zoneId));
virFilter &= virSecBuilder.Eq("IsActive", true);
var virtuSector = MongoContext.Sectors.Aggregate()
.Lookup("virtualChains", "_id", "VirtualChainId", "VirtualChains")
.Unwind("VirtualChains")
.Unwind("VirtualChains.ZoneConfigInfos")
.Match(virFilter)
.Project<SectorSummaryExIndex>("{Name:1,ArabicName:1,Code:1,ImageUrl:1,ArabicImageUrl:1,Index:1,Description:1,DescriptionAR:1,IsVirtual:1,StoreId:$VirtualChains.ZoneConfigInfos.StoreId}")
.ToList()
.OrderBy(c => c.Index);
return virtuSector;
但是如果我在展开之前添加
$
符号,则会抛出如下错误:
JSON 读取器需要一个值,但发现了“$VirtualChains”。
.Unwind("$VirtualChains")
我认为,如果您只是创建其名称为 VirtualChains 的结果模型,那么问题就会解决,然后您将通过第一步:
public class LookupModel : sectors {
public List<virtualChainModel> virtualChains {get;set;} // this part added to your sector model
}
public class UnwindeModel : sectors {
public virtualChainModel virtualChains {get;set;} // after unwind, added part is not a list any more
}
然后你可以像这样使用查找和展开:
var virtuSector = MongoContext.Sectors.Aggregate()
.Lookup<virtualChainModel,LookupModel>("virtualChains", "_id", "VirtualChainId", "VirtualChains")
.Unwind<UnwindeModel>("VirtualChains")
因为我没有你的 virtualChains 集合模型,所以我使用 virtualChainModel 代替,你应该在那里使用确切的实体模型。 我希望它对你有用。