看来我不明白我如何从文档中的集合中获得值。我在C#中使用MongoDB。

这是我的代码:

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

所以我的查询会寻找宠物猫。但是我不确定如何获得猫的名字。我尝试了几件事,但我大部分都将整个文档返回。

提前致谢,

pick

有帮助吗?

解决方案

这并不像我想要的那样优雅,因为我自己仍在学习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;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top