【问题标题】:Unable to convert MongoCursor to BsonDocument无法将 MongoCursor 转换为 BsonDocument
【发布时间】:2014-09-29 11:48:32
【问题描述】:

问题在于代码的“else”部分,其中变量“fields”从文档中接收所有指定的字段,但是在将其转换为 bson 并返回 bson 时,我得到一个错误:cannot在 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;
    }

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      相关资源
      最近更新 更多