justin
justin

Reputation: 31

How can i query or find by bsondocument in mongodb for C#

I have a BsonDocument like

{
    "_id" : "1db5b191-c6d5-47ea-90ef-98202f604a6b",
    "_P21id" : "#13",
    "_EntityName" : "IfcActorRole",
    "Role" : ".SUPPLIER.",
    "UserDefinedRole" : "$",
    "Description" : "$"
}

How can I query by this BsonDocument

{         
      "_EntityName" : "IfcActorRole",
      "Role" : ".SUPPLIER.",
      "UserDefinedRole" : "$",
      "Description" : "$"
}

Upvotes: 3

Views: 10162

Answers (2)

Mirtov
Mirtov

Reputation: 77

For lazy persons like me, use the following code : Database => test Collection => myCollection

 try
        {
            MongoClient client = new MongoClient();
            var db = client.GetDatabase("test");
            var collection = db.GetCollection<BsonDocument>("myCollection");
            var builder = Builders<BsonDocument>.Filter;
            var filter1 = builder.Eq("_id", "1db5b191-c6d5-47ea-90ef-98202f604a6b");
            using (var cursor = await collection.FindAsync(filter1))
            {
                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    foreach (var document in batch)
                    {

                            MessageBox.Show("entity name: " + document[2].ToString());
                            MessageBox.Show("role :" + document[3].ToString());
                            MessageBox.Show("user defined role :" + document[4].ToString());
                            MessageBox.Show("description :" + document[5].ToString());
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

Upvotes: 2

Anton Putau
Anton Putau

Reputation: 762

I guess you use mongosharp, and you need to exclude several fields from result?

    var items = new MongoClient(connectionString).GetDatabase(database).GetCollection<YOUR_CLASS>("items"); 

    var result = items.Find(query).Project(Builders<YOUR_CLASS>.Projection.Exclude(e => e.Property1).Exclude(e => e.Property2))

Upvotes: 1

Related Questions