BsonDocument contains an array. Need to access the array elements in C# when the BsonDocument is contained by a C# list

Rookie

I have a mongodb collection "users" which stores documents in the following format -

{
    "_id" : ObjectId("53fe7ae0ef038fee879263d5"),
    "username" : "John"
    "status" : "online",
    "profile" : [ 
        {
            "name" : "John Stuart",
            "age" : "23",
            "gender" : "male"
        }
    ]
}

I use the following function in C#.NET to store documents from the collection into a list of BsonDocuments -

    public static List<BsonDocument> LoadDataByWhere (string table, string whereClause)
    {
        // Here table is the collection name and whereClause is the mongodb query 

        var collection = db.GetCollection (table);
        QueryDocument whereDoc = new QueryDocument(BsonDocument.Parse(whereClause));
        var resultSet = collection.Find (whereDoc);
        List<BsonDocument> docs = resultSet.ToList();

        if (resultSet.Count() > 0) {
            foreach(BsonDocument doc in docs)
            {
                doc.Set("_id", doc.GetElement("_id").ToString().Split('=')[1]);
            }
            return docs;
        } 
        else {
            return null;
        }
    }

Supposing that I store the List returned in list. I can use -

    List<string> username = new List<string>();

    foreach(BsonDocument item in list) 
    {
        username.Add(Convert.ToString(list.getElement("username").Value));
    }

But how do I get the array element values like name, age and gender in C# using methods similar to the one described above?

RabidDog5150

I would recommend mapping the Mongo document to some form of DTO. Mongo supports deserializing into object graphs.

public class User
{   
    [BsonId]
    public ObjectId Id { get; set; }

    public string username { get; set; }

    public string status { get; set; }

    public List<Profile> profile { get; set; }
}


public class Profile
{

    public string name { get; set; }

    public string age { get; set; }

    public string gender { get; set; }
}

Then you can access it something like this

const string connectionString = "mongodb://localhost";

//// Get a thread-safe client object by using a connection string
var mongoClient = new MongoClient(connectionString);

//// Get a reference to a server object from the Mongo client object
var mongoServer = mongoClient.GetServer();

//// Get a reference to the database object
//// from the Mongo server object
const string databaseName = "mydatabase";
var db = mongoServer.GetDatabase(databaseName);

//// Get a reference to the collection object from the Mongo database object
//// The collection name is the type converted to lowercase + "s"
MongoCollection<T> mongoCollection = db.GetCollection<T>(typeof(T).Name.ToLower() + "s");

So when you query by id now it will contain the populated list of profiles, if they exist

use-csharp-driver

mongodb-with-c-deep-dive

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to pull ObjectId from an Array in a BsonDocument with C# MongoDriver 2.5

Mapping C# object to BsonDocument

MongoDB C# driver IAsyncCursor<BsonDocument> behavior?

Cannot convert BsonArray to BsonDocument in c#

xml parsing using c# (BsonDocument)

check if a list of array contains an array in c#

How to convert Future[BSONDocument] to list?

How to access array elements contained in a dictionary in swift

MongoDB - Update field or Add field if not present on BsonDocument C#

Extension methods for BsonDocument in C# from MongoDB 2.17

C# asp.net web api returning List<BsonDocument> how to keep Mongodb serializer from adding Name Value fields?

BsonDocument Serialized?

Is access to different elements in a C array thread safe?

How to access a field in a struct contained in an array of structs using a pointer to that array? [C++]

Access individual arrays or element of array when the array is an element of a list C#

Check If List Contains All Elements Of An Array

Firestore array contains query for list of elements

How to access in Swift a C struct that contains a variable sized array?

Objective-C PFQuery for string contained in an array?

Query MongoDB C#: how can I extract in a BsonDocument the field that results from calling aggregate method?

c - Access violation when reading array

Access violation when "resizing" array in C++

Sum of elements in a C array

Accessing array elements in c

sizeof array elements in C

C: Array elements disappearing

Sort elements in array C

Addition of an array elements in c

Dafny array elements contained in other array assertion