开发者

MongoDB + C#: Query inside a document

开发者 https://www.devze.com 2022-12-19 08:32 出处:网络
It seems I don\'t understand how I can get a value from a collection inside a document. I am using mongoDB in C#.

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


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消