我在MongoDB
个S文档中有一个集合。每个S
都有UserPermission objects
的集合,每个集合都有UserId
属性。我想选择S
具有特定UserPermission
的所有UserId
个文档:
return collection.Where(s => s.UserPermissions.Any(up => up.UserId == userIdString)).ToList();
我收到错误,告诉我不支持带有谓词的.Any
。 MongoDB文档说:“你通常可以通过在投影之前放置一个等效的where子句来重写这样的查询(在这种情况下你可以放弃投影)。”
这是什么意思?知道如何改变我的查询来解决这个限制吗?
这是一个完整的例子。您可以看到我尝试了两种不同的查询,但都不支持:
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; }
}
}
答案 0 :(得分:3)
Any()
,所以你可以这样做:
collection.Where(s => s.UserPermissions
.Where(up => up.UserId == userIdString).Any() )
(这是放在Any
之前的“等效where子句”)