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?
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments