U
U
ustus_alex2014-05-30 12:47:42
NoSQL
ustus_alex, 2014-05-30 12:47:42

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

And, there are classes describing it:
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();
    }

}

There is a method that inserts documents into a collection:
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);
    }

There is also a method that allows you to view the contents of the collection:
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;
}

In the MessageBox, the collection is displayed in its entirety, as it is:
ad23f5740bad47e39ba0d7b363fd268d.jpg
And, in the Datagridview, when I bind to allClients, I get the following output:
0a3c80928bd34745ad4dfad78c691e9d.jpg
How can I achieve to display the data from the nested document?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question