MongoDb C#从其他集合Map值

gblwokeq  于 2023-10-16  发布在  Go
关注(0)|答案(1)|浏览(131)

我必须收集,让我们说ColAColB

public sealed class ColA : IDatabaseObject
{
  [BsonId]
  public Guid Id { get; set; }

  [BsonElement("colb_id")]
  public Guid ColB_Id { get; set; }
}
public sealed class ColB : IDatabaseObject
{
  [BsonId]
  public Guid Id { get; set; }

  [BsonElement("title")]
  public string Title { get; set; }
}

我需要在一个投影ProjColA的结果,并通过ColA中的ColB_Id获得ColB的标题,但我不能做到这一点,有一种方法,而不是在2个单独的查询?

public sealed class Proj
{
  public Guid Id { get; set; }
  public Guid Colb_Id { get; set; }
  public string OtherTitleName { get; set; }
}
this.db.GetCollection<ColA>()
  .Aggregate()
  .Lookup<ColA, ColB, Proj>(
    this.db.GetCollection<ColB>(),
    a => a.ColB_Id,
    b => b.Id,
    // I need something like...
    a => new Proj {
      Id = a.Id,
      ColB_Id = a.ColB_Id,
      OtherTitleName = b.Title
    }
  )

查找是解决方案,还是我真的需要分两步完成?

aij0ehis

aij0ehis1#

var pipeline = new[]
{
    // Step 1: Lookup to join ColA and ColB
    new BsonDocument("$lookup",
        new BsonDocument
        {
            { "from", "ColB" },     // The foreign collection name (ColB)
            { "localField", "colb_id" },  // Field in ColA to match
            { "foreignField", "_id" },   // Field in ColB to match
            { "as", "colBData" }   // Alias for the joined data
        }
    ),
    
    // Step 2: Project the result as needed
    new BsonDocument("$project",
        new BsonDocument
        {
            { "Id", "$_id" }, // Include the _id from ColA
            { "Colb_Id", "$colb_id" }, // Include the colb_id from ColA
            { "OtherTitleName", "$colBData.title" } // Include the title from ColB
        }
    )
};

var result = this.db.GetCollection<ColA>()
    .Aggregate<Proj>(pipeline)
    .ToList();

相关问题