Find an specific element in a MongoDB document fro

2019-09-17 04:16发布

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?

2条回答
聊天终结者
2楼-- · 2019-09-17 04:24

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"}})
查看更多
叛逆
3楼-- · 2019-09-17 04:25

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.

查看更多
登录 后发表回答