2014-09-29 85 views
0

問題出在代碼的'else'部分,其中變量'fields'接收文檔中的所有指定字段,但在將其轉換爲bson並返回bson時,出現錯誤如:無法在bson文檔的根級寫入數組。無法將MongoCursor轉換爲BsonDocument

public BsonDocument bsonReadDocument(string strDbName, string strCollectionName, IMongoQuery query, string[] includeFields = null) 
    { 
     BsonDocument bsonDoc = null; 
     MongoServer MdbServer = ConnectToServer(); 

      if ((strDbName != "" || strDbName != null) && MdbServer.DatabaseExists(strDbName)) 
      { 
       if ((strCollectionName != "" || strCollectionName != null) && MdbServer.GetDatabase(strDbName.ToLower()).CollectionExists(strCollectionName)) 
       { 
        if (includeFields == null) 
        { 
         bsonDoc = MdbServer.GetDatabase(strDbName.ToLower()).GetCollection(strCollectionName.ToLower()).FindOne(query); 
        } 
        else 
        { 
         var fields = MdbServer.GetDatabase(strDbName.ToLower()).GetCollection(strCollectionName.ToLower()).Find(query).SetFields(Fields.Include(includeFields)); 
        } 
       } 
      } 
     } 
     return bsonDoc; 
    } 

回答

0

沒關係,我想通了「其他」的代碼塊中的解決方案我自己下面

MongoDatabase db = MdbServer.GetDatabase(strDbName); 
         MongoCollection<BsonDocument> collection = db.GetCollection(strCollectionName);       

         foreach (var document in collection.Find(query).SetFields(Fields.Include(includeFields).Exclude("_id"))) 
         { 
          foreach (string name in document.Names) 
          { 
           BsonElement element = document.GetElement(name); 
           BsonValue value = document.GetElement(name).Value; 
           bsonDoc.Add(element.Name, value); 
          } 
         }