MongoDB和C# Find()

18

我有以下代码,而且我是mongodb的新手,我需要帮助在集合中找到一个特定的元素。

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 = "admin",
            pwd = "admin"
        };
        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
         */
  }
}
}

我想找到用户并将其打印出来,这可行吗?还是find只返回位置?如果是的话,该如何打印呢?

我看过一些示例,如collection.Find(x => x.something),但我不知道x是什么或代表什么意思。

3个回答

44

要查找记录,您可以在find中使用Lambda,例如:

var results = collection.Find(x => x.name == "system").ToList();

你也可以使用构建器(Builders),这些构建器支持强类型 Lambda 或文本:

var filter = Builders<User>.Filter.Eq(x => x.name, "system")

或者

var filter = Builders<User>.Filter.Eq("name", "system")

然后像上面那样使用find

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

1
如果你在 .Find(x => x.name == "system") 中过滤,而不是之后的 .Find().Where(x => x.name == "system"),你会获得性能提升吗? - Egor Okhterov

4
它还取决于我们使用的 .Net 框架版本。如果我们使用 2x 驱动程序,它应该如下所示:
var list = await collection.Find(new BsonDocument()).ToListAsync();

方法2

await collection.Find(new BsonDocument()).ForEachAsync(X=>Console.WriteLine(X));

参考示例


0
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mongo_console
{
    class Program
    {
        public static void Main(string[] args)
        {
            MongoClient client = new MongoClient();
            MongoServer server = client.GetServer();
            MongoDatabase db = server.GetDatabase("admin");
            MongoCollection<Book> collection = db.GetCollection<Book>("Book");


            Book book1 = new Book
            {
                Id = ObjectId.GenerateNewId(),
                name = "Reel To Real"
            };
            Book book2 = new Book
            {
                Id = ObjectId.GenerateNewId(),
                name = "Life"
            };
            collection.Save(book1);
            collection.Save(book2);

            var query = Query<Book>.EQ(u => u.Id, new ObjectId("5a5ee6360222da8ad498f3ff"));
            Book list = collection.FindOne(query);
            Console.WriteLine( "Book Name  " + list.name);


            Console.ReadLine();
        }
    }
    public class Book
    {
        [BsonId]
        public ObjectId Id { get; set; }
        public string name { get; set; }

        public Book()
        {
        }

        public Book(ObjectId id, string name)
        {
            this.Id = id;
            this.name = name;
        }
    }
}

2
Builders似乎不再是一个有效的命名空间,而且类文档对我来说非常不清楚 - http://mongodb.github.io/mongo-csharp-driver/2.7/apidocs/html/T_MongoDB_Driver_Builders_1.htm是否有更新的示例?还是我完全错过了什么? - Vincent Buscarello

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接