MongoDb将文本搜索与其他查询结合使用(使用$或)

时间:2015-09-09 19:32:01

标签: c# mongodb mongodb-query

使用Mongo C#驱动程序(1.10)我正在尝试编写一个将文本搜索与其他一些过滤器结合起来的查询。注意:如果我将 OR 替换为 AND ,则执行查询。

    public IEnumerable<Asset> GetAssets(AssetSearch search)
    {
        var list = new List<IMongoQuery>();

        if (!string.IsNullOrEmpty(search.Text))
        {
            list.Add(Query.Or(
                Query.Text(search.Text), 
                Query<Asset>.Matches(a => a.FileName, search.Text)
            ));
        }

        if (search.FolderId.HasValue)
            list.Add(Query<Asset>.EQ(a => a.FolderId, search.FolderId.Value));

        return AssetCollection.Find(Query.And(list));
    }

执行(search.Text =“football”)

时出现此错误
"QueryFailure flag was Unable to execute query: error processing query: ns=db.assets limit=0 skip=0 Tree: $and $or filename regex /football/ TEXT : query=football, language=, tag=NULL folderId == ObjectId('55d72ad19b958b1e7c0506ff') Sort: {} Proj: {} No query solutions (response was { "$err" : "Unable to execute query: error processing query: ns=db.assets limit=0 skip=0\nTree: $and\n $or\n filename regex /football/\n TEXT : query=football, language=, tag=NULL\n folderId == ObjectId('55d72ad19b958b1e7c0506ff')\nSort: {}\nProj: {}\n No query solutions", "code" : 17007 })."

1 个答案:

答案 0 :(得分:0)

我尝试使用文字过滤器,但它对我不起作用。所以任何人都想用单一查询搜索多个列。你可以试试这个。

var filter = Builders<Book>.Filter.Or(
    Builders<Book>.Filter.Where(p=>p.Title.ToLower().Contains(query.ToLower())),
    Builders<Book>.Filter.Where(p => p.Publisher.ToLower().Contains(query.ToLower())),
    Builders<Book>.Filter.Where(p => p.Description.ToLower().Contains(query.ToLower()))
            );
List<Book> books = Collection.Find(filter).ToList();