2015-05-25 55 views
2

查詢或找到bsondocument有像我我怎麼能在MongoDB中爲C#

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

我怎樣才能通過這個BsonDocument

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

回答

1

我猜你使用mongosharp查詢,你需要一個BsonDocument從結果中排除幾個字段?

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

我認爲OP需要使用[投影](HTTP:// docs.mongodb.org/manual/tutorial/project-fields-from-query-results/)取回4個必填字段。 –

1

對於懶惰的人我一樣,使用以下代碼: 數據庫=>測試 類別=> 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); 
     }