Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to insert array into object mongodb

Tags:

arrays

c#

mongodb

Currently I am working on an application using C# where I want to add some data to a MongoDB collection. I am trying to add an array to an Employee object but I am struggling to get it working correctly.

When I am looking at other posts, I come across syntax using BsonDocument, something like this:

var document = new BsonDocument {
{ "author", "joe" },
{ "comments", new BsonArray {
    new BsonDocument { { "author", "jim" }, { "comment", "I disagree" } },
    new BsonDocument { { "author", "nancy" }, { "comment", "Good post" } }
}}

I want to add an array to Function attribute to add a description and other detailed info.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Core;

namespace Application
{
    class Program
    {
        public class Employee
        {
            public ObjectId Id { get; set; }
            public string BSN { get; set; }
            public string Name { get; set; }
            public string Function { get; set; 
        }

        static void Main(string[] args)
        {
            MongoClient client = new MongoClient();
            var server = client.GetServer();
            var db = server.GetDatabase("Database_Assignment");
            var collection = db.GetCollection<Employee>("Collection_Employees");

            Random random = new Random();

            List<string> names = new List<string>()        // Predefined list of names
            {
                "John Smith",
                "Matthew Williams",
                "David Harris",
                "Christopher Martin",
                "Paul Shark"
            };

            for (int i = 0; i < 5; i++)
            {
                int nameIndex      = random.Next(0, 5);         // Range in list of names
                int ageIndex       = random.Next(18, 67);       // Range for possible ages
                int funcIndex      = random.Next(0, 3);

                string nameValue   = names[nameIndex];         // Add index to string based on list of names
                string funcValue   = functions[funcIndex];     // Add index to string based on list of functions

                Employee employee = new Employee
                {
                    BSN = "BSN" + i,
                    Name = nameValue,
                    Function = funcValue
                };

                collection.Save(employee);
            }
        }
    }
}

Edit 1

This is what I currently have screenshot

This is what I am trying to accomplish screenshot

Taking the second screenshot for example, I want 'sensor_colle' to be Function and add some specific details to it. Hope this helps.

like image 916
Jason Hall Avatar asked Oct 17 '16 10:10

Jason Hall


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


1 Answers

If you want Function to be an array you should change it to that in your model, as it's currently just a string property, so:

public string[] Function { get; set; }

If an employee can have more than one function, or

public List<SomeFunctionObj> Function { get; set; 

If they can have multiple functions, and each function has multiple properties.

Have a look at

Builders<YourModel>.Update.Push

You will need to use the Update method instead of Save on the Collection if you are wanting to update an existing item instead of inserting it.

Alternatively

Builders<YourModel>.Update.AddToSet 

may be more appropriate if you are wanting to add an object to an array

I hope this helps, if i have misunderstood your question please let me know and i'll modify the answer as necessary

Update

If you want to add more information to the Function you will need to create an embedded model:

public class Employee
{
    public ObjectId Id { get; set; }
    public string BSN { get; set; }
    public string Name { get; set; }
    public EmployeeFunction Function { get; set; 
}

public class EmployeeFunction 
{
    public string FunctionDesc { get; set; }
    public string MoreInfo { get; set; }
}

So to populate it using your example code:

Employee employee = new Employee
            {
                BSN = "BSN" + i,
                Name = nameValue,
                Function = new EmployeeFunction 
                { 
                    FunctionDesc = funcValue, 
                    MoreInfo = "Some other info" 
                }
            };

This way, your mongodb document will look something like this:

{
...
    "Function" : {
        "FunctionDesc" : "Developer",
        "MoreInfo" : "Some other info"
    },
...
}
like image 64
pieperu Avatar answered Sep 21 '22 19:09

pieperu