无法将MongoCursor转换为BsonDocument

时间:2014-09-29 11:48:33

标签: c# mongodb mongodb-.net-driver mongodb-query

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

1 个答案:

答案 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);
                            }
                        }