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

本文关键字:使用 查询 其他 结合 文本 搜索 MongoDb | 更新日期: 2023-09-27 18:11:53

使用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));
    }

我得到这个错误时,执行(搜索)。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 })."

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

我试过使用文本过滤器,但它不适合我。所以任何人都想用一个查询在多个列中搜索。你可以试试这个

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();