Find an specific element in a MongoDB document from C#

别说谁变了你拦得住时间么 提交于 2019-12-13 04:43:25

问题


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"}]
        }
    ]
}

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.

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?


回答1:


You can use this code:

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

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

Step1: Define a full text-search on all fields via db.test.ensureIndex({"$**" : "text"});

Step2: Search your query db.test.find( { $text: { $search: "Type A" } } )

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




回答2:


Below aggregation query may solve your problem but I don't know how to write this in C#

db.collectioName.aggregate({"$unwind":"$Values"},
         {"$unwind":"$Values.Parameters"},
        {"$match":{"Values.Parameters.Type":"Type A"}},
       {"$group":{"_id":"$Values"}})


来源:https://stackoverflow.com/questions/27016837/find-an-specific-element-in-a-mongodb-document-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!