tags:

views:

270

answers:

1

Hello,

It seems I don't understand how I can get a value from a collection inside a document. I am using mongoDB in C#.

Here is my code:

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

So my query will look for the pet cat. But I am not sure how I can get the name of my cat. I tried a few things but I mostly get the whole document back.

Thanks in advance,

Pickels

+2  A: 

This isn't as elegant as I'd like as I'm still learning about MongoDB myself but it does show you one way to get the property you wanted.

[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;
    }
}
Handcraftsman
Ah so you do have to handle the query inside the document yourself. Was affraid I was missing something really obvious. Thanks a lot Handcraftsman
Pickels