简体   繁体   English

MongoDB + C#:在文档内部查询

[英]MongoDB + C#: Query inside a document

It seems I don't understand how I can get a value from a collection inside a document. 看来我不明白如何从文档中的集合中获取值。 I am using mongoDB in C#. 我在C#中使用mongoDB。

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. 尽管我自己还不了解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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM