2010-02-08 120 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