0

I currently have a mongodb filled with restaurants. Each restaurants has an array with review objects. I'm trying to retrieve a list of each review object in C#, but I can't get it to work.

So to clarify, I can get a restaurant, but I can't seem to get an List of just the review objects in C#.

I tried this, but it just returns the restaurant objects to me:

var coll = Database.GetCollection<Restaurant>("restaurants")
            .Aggregate()
            .Unwind(x => x.reviews);
        var result = await coll.ToListAsync();

        foreach(var r in result)
        {
            Console.WriteLine(r.ToString());
        }

This is my restaurant class:

public class Restaurant
{
    [BsonId]
    private ObjectId _id { get; set; }
    [BsonElement("name")]
    public string name { get; set; }
    [BsonElement("reviews")]
    public List<Review> reviews { get; set; }

    public Restaurant(string name)
    {
        _id = ObjectId.GenerateNewId();
        this.name = name;
        reviews = new List<Review>();
    }

    public void addReview(Review r)
    {
        reviews.Add(r);
    }

    public void removeReview(Review r)
    {
        reviews.Remove(r);
    }
}

Any help would be greatly appreciated!

4
  • stackoverflow.com/questions/33531808/… Commented Sep 6, 2016 at 12:58
  • I don't understand, what does that have to do with creating a list of items from an array? Commented Sep 6, 2016 at 13:09
  • 1
    I don't think that you receive restaurants object... In my code the unwind result to an array of BsonDocuments. But I didn't tested what's in the documents :) Commented Sep 6, 2016 at 13:12
  • Oh thank you! That made me think and I ended up fixing it, really appreciate it :D Commented Sep 6, 2016 at 13:21

1 Answer 1

1

You need a class function to return the name of the restaurant and the review object.

public String getName(Restaurant rest)
{
    return rest.name;
}

public List<Review> getReviews(Restaurant rest)
{
    return rest.reviews;
}

Edit: Sorry misunderstood the question. Hope this is what you were looking for now.

Sign up to request clarification or add additional context in comments.

2 Comments

Well that helps, but it still doesn't help me with creating Review objects
@Bas Added a function that should do that for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.