简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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