2014-09-29 89 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); 
          } 
         }