title: LINQ to MongoDB: .Any with a Predicate
body: <p>I have a Collection in <code>MongoDB</code> of S documents.  Each <code>S</code> has a collection of <code>UserPermission objects</code>, each of which have a <code>UserId</code> property.  I want to select all the <code>S</code> documents that have a <code>UserPermission</code> with a certain <code>UserId</code>:</p>
  
  <pre><code>return collection.Where(s =&gt; s.UserPermissions.Any(up =&gt; up.UserId == userIdString)).ToList();
  </code></pre>
  
  <p>I get an error telling me that <code>.Any</code> 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)."</p>
  
  <p>What does that mean? Any idea how I would change my query to get around this limitation?</p>
  
  <p>Here's a full example. You can see I've tried 2 different queries and neither is supported:</p>
  
  <pre><code>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&lt;User&gt;() 
                  { 
                      new User() { UserName = "Chris" } } 
                  };
  
              App app2 = new App() { Name = "App2", Users = new List&lt;User&gt;() 
                  { 
                      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&lt;App&gt;()
              //    .Where(a =&gt; a.Users.Any(u =&gt; u.UserName == "Carlos"));
  
              // Throws "Unsupported Where Clause" error.
              var query = appCollection.AsQueryable&lt;App&gt;()
                  .Where(a =&gt; a.Users.Where(u =&gt; u.UserName == "Carlos").Any());
  
              foreach (App loadedApp in query)
              {
                  Console.WriteLine(loadedApp.ToJson());
              }
              Console.ReadLine();
          }
      }
  
      class App
      {
          public string Name { get; set; }
          public List&lt;User&gt; Users { get; set; }
      }
  
      class User
      {
          public string UserName { get; set; }
      }
  }
  </code></pre>