Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: How to load collection with nested array in C#?

I have collection called "servers" with following documents.

{
    name: "West",
    ip: "123.123.123.123",
    channels:
    [
        {
            name: "English",
            port: "1234",
            status: "0"
        },
        {
            name: "Spanish",
            port: "1235",
            status: "0"
        },
        {
            name: "German",
            port: "1236",
            status: "0"
        }
    ]
},
{
    name: "East",
    ip: "122.122.122.122",
    channels:
    [
        {
            name: "English",
            port: "1234",
            status: "0"
        },
        {
            name: "French",
            port: "1235",
            status: "0"
        }
    ]
}

How would I select that from MongoDB using C# using structures?

like image 584
jM2.me Avatar asked Feb 27 '11 20:02

jM2.me


1 Answers

If you want all items you can use follwoing code:

var server = MongoServer.Create("mongodb://localhost:27020");
var database = server.GetDatabase("someDb");

var servers = database.GetCollection<ServerItem>("servers");
servers.FindAllAs<ServerItem>();

But if you want for example all documents with name = west, than you can:

collection.FindAs<ServerItem>(Query.EQ("name","west"));

ServerItem:

 public class ServerItem
 {
   public string name { get; set; }

   public string ip { get; set; }

   public List<Channel> channels { get; set; }
 } 

 public class Channel
 {
   public string name { get; set; }

   public int port { get; set; }

   public int status { get; set; }
 }
like image 118
Andrew Orsich Avatar answered Oct 05 '22 23:10

Andrew Orsich