簡體   English   中英

C# MongoDB.Driver 聚合與項目不返回字段_id

[英]C# MongoDB.Driver Aggregation with Project not returning the field _id

我的問題是對這種格式的文檔的查詢:

{
    "_id" : NumberLong(21),
    "_t" : "Detail",
    "Name": "Bank Z",
    "DeletionDate" : null,
    "CreationDate" : ISODate("2017-11-16T13:29:10.160Z"),
    "UpdateDate" : ISODate("2017-11-16T13:29:10.160Z"),
    "Accounts" : [ 
        {
            "Bank" : "123",
            "BankAccount" : "123456"
        }
    ]
}

我有這個 class 結構

細節.cs

[BsonDiscriminator("Detail")]
public class Detail
{

     public virtual long? Id { get; set; }
     public string Name { get; set; }

     [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
     public DateTime? DeletionDate { get; set; }

     [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
     public DateTime? CreationDate { get; set; }

     [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
     public DateTime? UpdateDate { get; set; }
     
     private IEnumerable<Account> _accounts;

     public IEnumerable<Account> Accounts {
         get
         {
             if (_accounts == null)
                 return new List<Account>();
             return _accounts;
         }
         set { _accounts = value;  } 
     }

}

帳戶.cs

public class Account
{
    public string Bank { get; set; }

    public string BankAccount { get; set; }
}

詢問

...
Collection.Aggregate().Match(filter).Project(det =>
                    new Details
                    {
                        Id = det.Id,
                        Name = det.Name,
                        UpdateDate = det.UpdateDate,
                        Accounts = det.Accounts.Where(x => x.Bank.Equals(Bank))
                    }).FirstOrDefault();

通過這個查詢,我可以將幾乎所有預填充的數據帶入 object 的實例中,但 _id 和 UpdateDate 都沒有填充。 查看 MongoDB.Driver 項目的 github 我看到誰在 Render 方法中刪除了 _id 字段。 我想知道是否有辦法扭轉這種情況,誰知道如何知道目的......

在 mongodb 中,查詢將如下所示:

db.getCollection('Detail').aggregate([
{ $match: { _id: 21 } },
{ 
    $project: { 
         
        UpdateDate: 1, 
        Name: 1, 
        SpecificAccounts: { $filter: { input: "$SpecificAccounts", as: "x", cond: { $eq: [ "$$x.Bank", "123" ] } } }
    }
}
])

我設法通過將整個查詢更改為 LINQ 來解決,我相信驅動程序在內部使用了另一種渲染方法。

 var q = from det in Collection.AsQueryable()
                    where det.Id == 21
                    select new Details
                    {
                        Id = det.Id,
                        Name = det.Name,
                        SpecificAccounts = det.SpecificAccounts.Where(x => x.Bank.Equals(getAccountDTO.Bank))
                    };

var resp = q.ToList().FirstOrDefault();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM