1

I have a collection on MongoDb with a similar stricture to the object below.

{
    _id: ObjectId("0000000"),
    groupName: "Group A",
    users[
        {
            userId: "1111111",
            rollDescription: "Some Text Here"
        },
        {
            userId: "2222222",
            rollDescription: "Some Text Here"
        },
        {
            userId: "3333333",
            rollDescription: "Some Text Here"
        }
    ]
}

Elsewhere in the system an array of "userIds" is generated and I need to select all groups that contain all userIds in the array.

Is it possible to do this using just linq?

I know I can use this if I had just an array of userIds:

from g in groups.AsQueryable<Group>() where g.Users.ContainsAll(usersIds.ToArray()) select g;

Is there something similar for querying an array of subdocumnets instead of an array of strings?

1 Answer 1

1

Here's how I'd do it in a MongoDB query:

db.collection.find({ "users.userId": { $all: [ "1111111", "2222222", "3333333" ] }})

I think LINQ will be quite a bit trickier. Does this work (I don't have MongoDB installed)?

from g in groups.AsQueryable<Group>() where g.Users.ConvertAll(u => g.UserId).AsQueryable().ContainsAll(userIds) select g;

Even if it did I suspect that it will not be as performant as using the MongoDB query builder:

groups.Find(Query.All("users.userId", userIds))
Sign up to request clarification or add additional context in comments.

2 Comments

The LINQ compiles with the following change"ConvertAll(u => u.UserId)" but on runtime I get the error: Unable to determine the serialization information for the expression: Queryable.AsQueryable<String>(g.Users.ConvertAll<String>((User u)=> u.UserId)). I have been unable to solve the error so far. The solution using groups.Find is working. I just had to make the following change "groups.Find(Query.All("users.userId", new BsonArray(userIds)))"
It would still be nice to get this fully working with LINQ since the system is in development, and it avoids people renaming things and breaking the query, but for now the Mongo query works.

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.