2010-02-08 134 views
0

看來我不明白我如何從文檔中的集合獲取價值。我在C#中使用mongoDB。MongoDB + C#:查詢文檔內

這裏是我的代碼:

var jimi = new Document(); 

jimi["Firstname"] = "Jimi"; 
jimi["Lastname"] = "James"; 
jimi["Pets"] = new[] 
{ 
    new Document().Append("Type", "Cat").Append("Name", "Fluffy"), 
    new Document().Append("Type", "Dog").Append("Name", "Barky"), 
    new Document().Append("Type", "Gorilla").Append("Name", "Bananas"), 
}; 

test.Insert(jimi); 

var query = new Document().Append("Pets.Type","Cat"); 

所以我的查詢將尋找寵物貓。但我不知道我怎麼能得到我的貓的名字。我嘗試了一些東西,但我主要把整個文檔都拿回來了。

由於提前,

Pickels

+0

退房=> http://highoncoding.com/Articles/680_Implementing_Business_Object_to_Documents_Converter_for_MongoDb.aspx到實體轉換成文檔。 – azamsharp 2010-03-08 04:46:21

回答

3

這不是優雅,因爲我想爲我還在學習有關MongoDB的自己,但它並告訴你一個方法來獲得你想要的屬性。

[TestFixture] 
public class When_working_with_nested_documents 
{ 
    [Test] 
    public void Should_be_able_to_fetch_properties_of_nested_objects() 
    { 
     var mongo = new Mongo(); 
     mongo.Connect(); 
     var db = mongo.getDB("tests"); 
     var people = db.GetCollection("people"); 

     var jimi = new Document(); 

     jimi["Firstname"] = "Jimi"; 
     jimi["Lastname"] = "James"; 
     jimi["Pets"] = new[] 
     { 
      new Document().Append("Type", "Cat").Append("Name", "Fluffy"), 
      new Document().Append("Type", "Dog").Append("Name", "Barky"), 
      new Document().Append("Type", "Gorilla").Append("Name", "Bananas"), 
     }; 

     people.Insert(jimi); 

     var query = new Document(); 
     query["Pets.Type"] = "Cat"; 
     var personResult = people.FindOne(query); 
     Assert.IsNotNull(personResult); 
     var petsResult = (Document[])personResult["Pets"]; 
     var pet = petsResult.FindOne("Type", "Cat"); 
     Assert.IsNotNull(pet); 
     Assert.AreEqual("Fluffy", pet["Name"]); 
    } 
} 

public static class DocumentExtensions 
{ 
    public static Document FindOne(this Document[] documents, string key, string value) 
    { 
     foreach(var document in documents) 
     { 
      var v = document[key]; 
      if (v != null && v.Equals(value)) 
      { 
       return document; 
      } 
     } 
     return null; 
    } 
} 
+0

啊,所以你必須自己處理文檔中的查詢。很害怕我錯過了一些非常明顯的東西。 非常感謝Handcraftsman – Pickels 2010-02-09 13:54:00