Search code examples
c#mongodbmongodb-.net-drivermongodb-query

Unable to convert MongoCursor to BsonDocument


The problem lies in the 'else' part of the code where the variable 'fields' recieves all the specified fields from the document, but while converting it to bson and returning bson ,i get an error as : cannot write array at the root level of a bson document.

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;
    }

Solution

  • Never mind, i figured out the solution for the 'else' code block on my own below

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