简体   繁体   English

使用C#从MongoDB中检索整个数组

[英]retrieving entire array from MongoDB with C#

I'm trying to retrieve all documents inside an array, and I want to put all of these in a list in C#. 我正在尝试检索数组中的所有文档,并且想将所有这些文档放入C#的列表中。

I have a class called Subject with an list of users, called followers. 我有一个名为Subject的类,其中包含一个用户列表,称为关注者。 It's defined like this: 它的定义如下:

public class Subject
{
    public Guid _id { get; set; }
    public List<User> Followers { get; set; }
}

and I'm using this function: 我正在使用此功能:

await db.Subjects.Find( FILTER HERE ).ToListAsync();

I just can't seem to get it to work, any help would be appreciated! 我似乎无法正常工作,将不胜感激!

Edit: This is my document structure for my subjects 编辑:这是我主题的文档结构

{
    "_id" : BinData(3,"/mRuH9AiWEiEJV2Ad0UAVg=="),
    "name" : "Subject test",
    "address" : {
            "Street" : "Street Test",
            "Postalcode" : "1234AB",
            "City" : "City Test",
            "CountryCode" : "NL",
            "Telephone" : "0612345678",
            "Coordinates" : {
                    "Longitude" : "1234",
                    "Latitude" : "1234"
            }
    },
    "Followers" : [
            DBRef("Name test", BinData(3,"uwXp/avTGEeeaR0muzYvOA==")),
            DBRef("Name test", BinData(3,"dK15dIEW302RWg/F1b+rtg=="))
    ],
    "Chefs" : [ ],
    "Owners" : [ ]
}

and my user structure: 和我的用户结构:

{
    "_id" : BinData(3,"uwXp/avTGEeeaR0muzYvOA=="),
    "name" : "Name test",
    "loginDate" : ISODate("0001-01-01T00:00:00Z"),
    "followers" : [ ]
}

Is it throwing an error or is it just empty ? 是引发错误还是仅仅是空的?

var MySubjets = await db.Subjects.Find( FILTER HERE ).ToListAsync();

Has to return an array of subjects matching your filter. 必须返回与您的过滤器匹配的主题数组。

Is that what you want? 那是你要的吗? Or are you looking for the "Followers" array ? 还是您在寻找“跟随者”数组?

var MySubject = await db.Subjects.Find( FILTER HERE ).FirstOrDefault();
foreach (User MyFollower in MySubject.Followers)
{
   //do your stuff...
}

But another major thing, is there data in the collection and does the fields correspond to the class properties? 但是另一件事是,集合中是否有数据,并且字段是否对应于类属性? When not you have to use classmappings 不需要时,您必须使用类映射

For the DBRefs do something like: 对于DBRef,请执行以下操作:

var MySubject = await db.Subjects.Find( FILTER HERE ).FirstOrDefault();
foreach (var MyRelatedDocument in MySubject.Followers)
{
    User MyFollower = db.FetchDBRefAs<User>(MyRelatedDocument);
   //do your stuff...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM