无法检索mongodb中的子文档项c#

时间:2015-01-17 05:40:10

标签: c# asp.net-mvc mongodb pagination mongodb-.net-driver

模型结构:

//Main doc model
Public class MainDocumentModel
{
   [BsonId]
   [BsonRepresentation(BsonType.ObjectId)]
   public string Id { get; set; }

   public string Name{ get; set; }
   public List<SubDocuementModel> SubDocsList { get; set; }
}

//sub doc model
Public class SubDocumentModel
{
   public string Id { get; set; }

   [BsonIgnoreIfNull]
   public string MainDocId { get; set; }
   public string Name{ get; set; }

   [BsonIgnoreIfNull]
   public List<SubDocuementModel> SubDocsList { get; set; } 
   .
   .
   .
}

当我插入MainDocuement时,在DB中,其结构如下:

{
    "_id" : ObjectId("54b9d732bb63bc10ec9bad6f"),
    "Name" : "Name-1",
    "SubDocsList  : [{
        "Id" : "54b9e76dbb63bc1890e8761b",
        "Name" : "Sub-Name-1"
    },....]
}

现在我想检索main doc Id == 54b9d732bb63bc10ec9bad6f

所在的子文档
private void getSubDoc(SubDocumentModel oModel)
{
  _MainDoc = _db.GetCollection<MainDocumentModel>("MainDoc");
  _query =  Query<MainDocumentModel>.Where(e => e.Id == oModel.MainDocId);

  //Here I get the exception
  //Exception: An error occurred while deserializing the SubDocsList property
  of class Data.MainDocumentModel: Element 'Id' does not match any field or
  property of class Data.SubDocumentModel.
  private MainDocumentModel _mainDocModel = _MainDoc.FindOneAs<MainDocumentModel>(_query);

 oModel.SubDocsList =
                        _mainDocModel .SubDocsList .FindAll(
                            x => x.Name.ToLower().Contains("NameFilter"));

 //Pagination 
 oModel.SubDocsList =
                        oModel.SubDocsList .Take(oModel.ItemsPerPage)
                            .Skip(oModel.ItemsPerPage*(oModel.PageNo - 1))
                            .ToList();
}
  1. 为什么我要超越反序列化异常。我做错了什么?

  2. 这里我将分页逻辑应用于检索到的c#列表。如何在mongo查询中应用分页本身?

  3. 为主要文档应用分页非常容易:

    mainDocCursor = MainDoc .Find(_query).SetSortOrder(SortBy.Ascending("Name")).SetLimit(oModel.ItemsPerPage).SetSkip(oModel.ItemsPerPage * (oModel.PageNo - 1));
    

    如何为子文档实现相同的分页?

1 个答案:

答案 0 :(得分:0)

我解决了反序列化的例外,并进行了以下小改动:

在SubDocumentModel中:

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

当我插入子文档时,我将 Id作为对象ID 保存为不是字符串(之前我将其保存为导致问题的字符串):

public void addSubDocument(SubDocumentModeloModel)
{
    _MainDoc = _db.GetCollection<MainDocumentModel>("MainDoc");
    BsonDocument subDocument = new BsonDocument
    {
       {"_id", ObjectId.GenerateNewId()},//Previously it was {"Id", ObjectId.GenerateNewId().ToString()}
       {"Type", oModel.Name}
    };

    _query = Query<MainDocumentModel>.Where(e => e.Id == oModel.MainDocId);
    _updateBuilder = Update.Push("SubDocsList", subDocument);
    _MainDoc.Update(_query, _updateBuilder);
}

但是我还没有找到mongodb-c#

中子文档分页的方法