Search code examples
c#mongodbmongodb-.net-driver

Find an specific element in a MongoDB document from C#


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?


Solution

  • 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.