简体   繁体   中英

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#.

I have a class called Subject with an list of users, called followers. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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