2

folowing situation: I have a list of Users, evry one have a field with a List of Comments.

User1: {
      ...
      Id : 'xxxx',
      Comment : [{
                   ...
                   Status : 1
                }
                ,{
                   ...
                   Status : 0
                }]
}

I am looking for a Mongo c# Query that select all Comments with status 1 of all users in the DB Collection.

sry for bad English.

thx

1
  • You can't do that in MongoDB directly. It doesn't support returning only matching array elements. It's either only the first match, or all. You'd need to do a filter on the client. Commented Apr 10, 2014 at 16:24

2 Answers 2

2

Let's assume you have the following classes that contain the serialized values for your collection:

public class User1
{
    public string Id { get; set; }

    public Comment[] Comments { get; set; }
}

public class Comment
{
   public int Status { get; set; }
}

Then the query should be something like:

var query =
    collection.AsQueryable<User1>().SelectMany(user => user.Comments.Where(com=>com.Status == 1));
Sign up to request clarification or add additional context in comments.

1 Comment

That won't work. SelectMany isn't supported in MongoDB's Official LINQ implementation.
0

thx.

I slove it like this:

var query1  =  Query.EQ("Comments.Status", 1)
IEnumerable<Comment> comments = Collection.Distinct<Comment>("Comments", query1).Where(x => x.Status == 1);

comments .toList() // <= list of Comments with Status 1

if someone has a better solution please post it.

Thx again,

Benjamin

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.