Christopher
Christopher

Reputation: 95

LINQ to MongoDB: .Any with a Predicate

I have a Collection in MongoDB of S documents. Each S has a collection of UserPermission objects, each of which have a UserId property. I want to select all the S documents that have a UserPermission with a certain UserId:

return collection.Where(s => s.UserPermissions.Any(up => up.UserId == userIdString)).ToList();

I get an error telling me that .Any with a predicate is not supported. The MongoDB docs say: "You can usually rewrite such a query by putting an equivalent where clause before the projection (in which case you can drop the projection)."

What does that mean? Any idea how I would change my query to get around this limitation?

Here's a full example. You can see I've tried 2 different queries and neither is supported:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;

namespace MongoSample
{
    class Program
    {
        static void Main(string[] args)
        {
            App app1 = new App() { Name = "App1", Users = new List<User>() 
                { 
                    new User() { UserName = "Chris" } } 
                };

            App app2 = new App() { Name = "App2", Users = new List<User>() 
                { 
                    new User() { UserName = "Chris" }, 
                    new User() { UserName = "Carlos" } } 
                };

            MongoServer server = MongoServer.Create();
            MongoDatabase database = server.GetDatabase("test");
            MongoCollection appCollection = database.GetCollection("app");

            appCollection.Insert(app1);
            appCollection.Insert(app2);

            // Throws "Any with a predicate not supported" error
            //var query = appCollection.AsQueryable<App>()
            //    .Where(a => a.Users.Any(u => u.UserName == "Carlos"));

            // Throws "Unsupported Where Clause" error.
            var query = appCollection.AsQueryable<App>()
                .Where(a => a.Users.Where(u => u.UserName == "Carlos").Any());

            foreach (App loadedApp in query)
            {
                Console.WriteLine(loadedApp.ToJson());
            }
            Console.ReadLine();
        }
    }

    class App
    {
        public string Name { get; set; }
        public List<User> Users { get; set; }
    }

    class User
    {
        public string UserName { get; set; }
    }
}

Upvotes: 3

Views: 2955

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109185

Any() without a predicate is supported, so you can do:

collection.Where(s => s.UserPermissions
    .Where(up => up.UserId == userIdString).Any() )

(this is the "equivalent where clause" put before the Any)

Upvotes: 3

Related Questions