MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Simple Customer Database how to add several orders to the same Customer

Hi,

I am pretty new to NoSQL and to MongoDB :wink:

I have a beginner question maybe someone could help me. I would like to try out a simple CustomerDB.

I am using MongoDB Atlas and C# Driver in Visual Studio.

My data should look something like this:

{
    CustomerNr,
    Lastname,
    Order1("Toothbrush", "Soap", ...)
    Order2("Book","Paper","Milk", ...)
}

And if the Customer orders next time I would like to add a Order3 in the document. Next Order add Order4 etc.

How do I have to write my C# Class to accomplish this?

public class CustomerModel
    {
        [BsonId]
        public Guid ID { get; set; }
        public Int64 CustomNr { get; set; }
        public string LastName { get; set; }
        public ??? ORDER ???
}

public class OrderModel
{
     ?????
}

and later on create that instance

var x = new CustomModel(1,"Smith", ????)

I hope someone understands what I am asking for :slight_smile:

Thx for Help

In the MongoDB your customer collection’s document will store the orders as an array of order objects. In general, MongoDB data structure is that a database has collections and collection has documents (see MongoDB Introduction).

{
    customerNr: 123,
    lastname: "Smith",
    orders: [
            { orderNo: 1, items: [ "Toothbrush", "Soap", ... ] },
            { orderNo: 2, items: [ "Book", "Paper", "Milk", ... ] },
            ...
    ]
}

What is ??? ORDER ???:

public class CustomerModel
{
        [BsonId]
        public Guid ID { get; set; }
        public Int64 CustomNr { get; set; }
        public string LastName { get; set; }
        public ??? ORDER ???
}

This is to be a List collection, like List<OrderModel>. And the OrderModel class might look like:

public class OrderModel
{
     public Int64 OrderNo { get; set; }
     public List<string> Items { get; set; }
}

Creating the Customer Instance:

What will be ??? in var x = new CustomModel(1, "Smith", ????)

var order1 = new OrderModel( 1, new List<string> { "Toothbrush", "Soap" } )
var order2 = new OrderModel( 2, new List<string> { "Book", "Paper", "Pencils" } )
var x = new CustomModel(1, "Smith", new List<OrderModel> { order1, order2 } )

NOTE: I have never worked with C# before; I know Java programming language and both have similar OO concepts of classes, collections, etc., and I have written based on that.

Useful Reference: Data model introduction