无法将MongoCursor转换为BsonDocument

本文关键字:BsonDocument 转换 MongoCursor | 更新日期: 2023-09-27 18:25:00

问题在于代码的'else'部分,其中变量'fields'接收文档中的所有指定字段,但在将其转换为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;
    }

无法将MongoCursor转换为BsonDocument

没关系,我自己在下面找到了'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);
                            }
                        }