Answer the question
In order to leave comments, you need to log in
How to view nested document in MongoDB collection (MongoDB C# Driver)?
Good afternoon, I'm interested in the question of how it is possible to view the contents of nested documents in collections using the MongoDB C# Driver.
There is a collection of something like this:
{
"_id" : ObjectId("5387548bd77a951d4006decd"),
"AccountNr" : 123,
"FirstName" : "Martin",
"LastName" : "Marley",
"Address" : {
"Zip" : 40789
}
}
public class Address
{
[BsonElementAttribute("Zip")]
public int Zip { get; set; }
[BsonElementAttribute("City")]
public string City { get; set; }
[BsonElementAttribute("Street")]
public string Street { get; set; }
[BsonElementAttribute("HomeNr")]
public int HomeNr { get; set; }
}
public class Client
{
[BsonId]
public ObjectId _id { get; set; }
[BsonElementAttribute("AccountNr")]
public int AccountNr { get; set; }
[BsonElementAttribute("FirstName")]
public string FirstName { get; set; }
[BsonElementAttribute("LastName")]
public string LastName { get; set; }
[BsonElementAttribute("Address")]
public Address address { get; set; }
[BsonConstructor]
public Client()
{
address = new Address();
}
}
public void InsertCustomer(Client client )
{
MongoCollection<Client> document = myDatabase.GetCollection<Client>("Client");
BsonDocument Client = new BsonDocument
{
{"AccountNr",client.AccountNr},
{"FirstName",client.FirstName},
{"LastName",client.LastName},
{"Address", new BsonDocument{{"Zip",client.address.Zip}}}
};
document.Insert(Client);
}
public List<Client> ViewAllClientsList()
{
var collection = myDatabase.GetCollection<Client>("Client");
MongoCursor<Client> clientResults = collection.FindAllAs<Client>();
List<Client> allClients = clientResults.ToList<Client>();
MessageBox.Show(allClients.ToJson().ToString());
return allClients;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question