我如何在mongodb中通过bsondocument查询或查找C#

时间:2015-05-25 14:09:50

标签: c# mongodb mongodb-query

我有一个类似

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

如何通过此BsonDocument查询

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

2 个答案:

答案 0 :(得分:2)

对于像我这样的懒人,请使用以下代码: 数据库=>测试 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);
        }

答案 1 :(得分:1)

我猜你使用mongosharp,你需要从结果中排除几个字段吗?

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