我有一个MongoDB
S 文件的集合。每个S
都有一个集合UserPermission objects
,每个集合都有一个UserId
属性。我想选择所有具有特定的S
文档:UserPermission
UserId
return collection.Where(s => s.UserPermissions.Any(up => up.UserId == userIdString)).ToList();
我收到一条错误消息,告诉我.Any
不支持使用谓词。MongoDB 文档说:“您通常可以通过在投影之前放置等效的 where 子句来重写这样的查询(在这种情况下,您可以删除投影)。”
这意味着什么?知道如何更改查询以绕过此限制吗?
这是一个完整的例子。您可以看到我尝试了 2 个不同的查询,但都不支持:
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; }
}
}