MongoDB:如何在C#中使用嵌套数组加载集合?

时间:2011-02-27 20:07:25

标签: c# mongodb mongodb-.net-driver

我有一个名为“servers”的集合,包含以下文档。

{
    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"
        }
    ]
}

我如何使用C#using结构从MongoDB中选择它?

1 个答案:

答案 0 :(得分:7)

如果您想要所有项目,请使用以下代码:

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

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

但是,如果你想要所有名字=西的文件,你可以:

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