从C#查找MongoDB文档中的特定元素 [英] Find an specific element in a MongoDB document from C#

查看:85
本文介绍了从C#查找MongoDB文档中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从C#ASP.NET应用程序访问MongoDB.

I am trying to access MongoDB from C# ASP.NET application.

假设,我有一个像下面这样的文件-

Let's assume, I've a document like below-

{
    "_id" : ObjectId("546c776b3e23f5f2ebdd3b03"),
    "Name" : "Test",
    "Values" : [ 
        {
            "Name" : "One",
            "Value" : 1
        }, 
        {
            "Name" : "Two",
            "Value" : 2,
            "Parameters": [{"Type": "Type A"}, {"Type": "Type B"}]
        }
    ]
}

请注意,只有_idName元素是固定的.其他元素由用户动态创建,其中键和值均由用户定义.

Please note that, only the _id and Name elements are fixed; other elements are dynamically created by the user where both the key and value are defined by the user.

现在,我想搜索值为Type A的元素Type.如何从MongoDB C#驱动程序执行此操作?

Now, I would like to search for the element Type with the value Type A. How can I do this from a MongoDB C# driver?

推荐答案

您可以使用以下代码:

var query = Query.EQ("Values.Parameters.Type", "Type A");
var items = collection.Find(query).ToList();

如果您的数据具有结构,请使用以下内容:

If you data has structure use this:

var items = collection.FindAs<Item>(query).ToList();

修改: 对于动态搜索,我想到的唯一方法是全文搜索:

For dynaically search the only way comes to my mind is full-text-search:

第1步:通过db.test.ensureIndex({"$**" : "text"});

第二步:搜索您的查询db.test.find( { $text: { $search: "Type A" } } )

如果是您的答案,那么C#代码应该很简单.

If its your answer, the C# code should be easy.

这篇关于从C#查找MongoDB文档中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆