问题在于“其他”'变量'字段'的部分代码收到文档中的所有指定字段,但在将其转换为bson并返回bson时,我收到错误:无法在bson文档的根级别写入数组。
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 :(得分:0)
没关系,我在下面想出了'else'代码块的解决方案
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);
}
}