简体   繁体   English

c#mongodb查找带有给定项目列表的所有文档。 否则返回所有文件

[英]c# mongodb find all document with a give item of a list. Otherwise return all documents

The requirements is "Find all the posts with the given tag if it exists. Otherwise, return all the posts". 要求是“查找具有给定标签的所有帖子(如果存在)。否则,返回所有帖子”。 And I try the following 我尝试以下

[HttpGet]
public async Task<ActionResult> Posts(string tag = null)
{
    var blogContext = new BlogContext();
    var posts = await blogContext.Posts.Find(Builders<Post>.Filter.AnyEq(x => x.Tags, tag)   )
                     .Sort(Builders<Post>.Sort.Descending("CreatedAtUtc")).ToListAsync();

    return View(posts);
}

My question is how to retrieve all documents when it is not match? 我的问题是当不匹配时如何检索所有文档? thanks, 谢谢,

我知道了。

    var posts = await blogContext.Posts.Find(x => (string.IsNullOrEmpty(tag) || x.Tags.Contains(tag))).Sort(Builders<Post>.Sort.Descending("CreatedAtUtc")).ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM