首页 > 解决方案 > MongoDB C# 驱动程序 - 使用未加入数组的查找(聚合)

问题描述

我正在尝试通过使用查找(聚合)的 ID 加入两个集合。两个班:

public class Accountant
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public ObjectId Id { get; set; }

    [BsonElement("bestClientsIds")]
    [BsonRepresentation(BsonType.ObjectId)]
    public string[] BestClientsIds { get; set; }

    public List<Client> MyClients { get; set; }
}
public class Client
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)] 
    public ObjectId Id { get; set; }

    [BsonElement("clientName")]
    public string Name { get; set; }
}

查询:

IMongoCollection<Accountant> collection = mongoDatabase.GetCollection<Accountant>("accountants");
IMongoCollection<Client> foreignCollection = mongoDatabase.GetCollection<Client>("clients");

                var results = collection.Aggregate()
                    .Lookup<Accountant, Client, Accountant>(
                        foreignCollection: foreignCollection,
                        localField: ac => ac.BestClientsIds,
                        foreignField: c => c.Id,
                        @as: ac => ac.MyClients
                    ).ToList().AsQueryable();

文件:

accountants:
_id:ObjectId("5deea64bfb49b60019a4ac97")
active:true
bestClientsIds:Array
    0:"5de95d449f4b820413c89e11"
    1:"5d2c1cfb8f4b810011c89e14"
    2:"5d3c1e5a5f4b81e045c89e52"
__v:11


clients:
_id:ObjectId("5d3c1e5a5f4b81e045c89e52")
active:true
clientName:"John Doe"
__v:6

_id:ObjectId("5de95d449f4b820413c89e11")
active:true
clientName:"Mike Davis"
__v:6

我不知道为什么这不起作用。连接不会发生,因为ac.MyClients没有元素,即使ac.BestClientsIds数组有。据我了解,$lookup 支持数组。我真的很感激一些帮助。谢谢。(MongoDB v4.2.3,.Net Driver v2.10.1,数据类型不可修改)。

标签: c#mongodbmongodb-querymongodb.driver

解决方案


推荐阅读