2010-02-08 4 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"); 

그래서 내 쿼리가 애완 동물 고양이를 찾습니다 :

여기 내 코드입니다. 그러나 나는 어떻게 내 고양이의 이름을 얻을 수 있는지 잘 모르겠다. 몇 가지 시도했지만 대부분 전체 문서를 다시 가져옵니다. 난 여전히 MongoDB에 대해 배우고 나는 나 자신을 싶지만 그것은 당신에게 당신이 원하는 속성을 얻을 수있는 한 가지 방법을 보여 않는 한이 우아하지 않다 미리

감사합니다,

Pickels

+0

체크 아웃 => http://highoncoding.com/Articles/680_Implementing_Business_Object_to_Documents_Converter_for_MongoDb.aspx 문서로 엔티티를 변환합니다. – azamsharp

답변

3

.

[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

아, 문서 내에서 직접 쿼리를 처리해야합니다. affraid 나는 정말로 명백한 무엇인가 놓치고 있었다. 고맙습니다. 수공예가 – Pickels