Home > Blockchain >  How to find a document with Bson type in mongo in c#
How to find a document with Bson type in mongo in c#

Time:03-27

I want to find a role details with specified username in MongoDb with Drivers in C#. I don't want to use any builders or linq methods.

I tried this to insert a Bson document and it worked.

            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("test");
            var collec = database.GetCollection<BsonDocument>("user");

            var documnt = new BsonDocument{
                {"username", txtUsername.Text},
                {"password", txtPassword.Password}
            };
            var check_count = collec.CountDocuments(documnt);

But when I tried this code to find a role with username its not working:

            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("test");
            var collec = database.GetCollection<BsonDocument>("user");
            var documnt = new BsonDocument{
                {"username", "admin"},
                {"role", 1}
            };
            var role = collec.Find(documnt);
            txtTestRole.Text = role.ToString();

I got this as output: enter image description here

CodePudding user response:

You have to materialize the query.

As you query for single record, you can use IAsyncCursorSourceExtensions.SingleOrDefault Method.

Or you can refer to IFindFluent (Extension methods section) to select the method that is best suited to you.

Next, from returned BsonDocument to select the specific field for the displayed value.

var user = collec.Find(documnt)
    .SingleOrDefault();

if (user == null)
{
  // Handle user not exist
  return;
}

txtTestRole.Text = user["role"].ToString();
  • Related