MongoDB 和 C# Find()
- 作者: 我的相册里全是风景
- 来源: 51数据库
- 2022-10-28
问题描述
我有以下代码,我是 mongodb 的新手,我需要帮助来查找集合中的特定元素.
I have the below code and I am new to mongodb, I need help in finding an specific element in the collection.
using MongoDB.Bson;
using MongoDB.Driver;
namespace mongo_console {
public class User {
public ObjectId Id { get; set; }
public string name { get; set; }
public string pwd { get; set; }
}
class Program {
static void Main(string[] args)
{
MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("Users");
MongoCollection<User> collection = db.GetCollection<User>("users");
User user = new User
{
Id = ObjectId.GenerateNewId(),
name = "*****",
pwd = "*****"
};
User user2 = new User
{
Id = ObjectId.GenerateNewId(),
name = "system",
pwd = "system"
};
collection.Save(user);
collection.Save(user2);
/*
* How do I collection.Find() for example using the name
*/
}
}
}
一旦我找到我想要打印的用户,这是可能的还是只会找到返回位置?如果是这样,我该如何打印?
Once I find the user I will like to print it, is that posible or will find only return the position? if so, how do I print it?
我看过一些示例 collection.Find(x => x.something) 但我不知道 x 是什么或意味着什么
I have seen some examples collection.Find(x => x.something) but I do not know what that x is or mean
推荐答案
要查找记录,您可以在 find 中使用 Lambda,例如:
To find a record you could use Lambda in find, for example:
var results = collection.Find(x => x.name == "system").ToList();
或者,您可以使用支持强类型 Lambda 或文本的构建器:
Alternatively you can use Builders which work with strongly typed Lambda or text:
var filter = Builders<User>.Filter.Eq(x => x.name, "system")
或
var filter = Builders<User>.Filter.Eq("name", "system")
然后像上面一样使用find
And then use find as above
// results will be a collection of your documents matching your filter criteria // Sync syntax var results = collection.Find(filter).ToList(); // Async syntax var results = await collection.Find(filter).ToListAsync();
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
