C# MongoDB filter a value from the following structure

Hello,

I have the following document structure:
Untitled

I’m using the latest C# MongoDB driver and I am trying to retrieve only the documents with Value of “11111” for instance.

I’ve tried the following filter:

var filter = Builders.Filter.Eq(“Parameters.Value”, “11111”);

This does not return any documents (yet on Compass { Parameters.Value: “11111” } returns the document in question.

What might I be doing wrong? Any help would be appreicated.

Hi, @Matan_Cohen,

Welcome to the MongoDB Community. I understand that you’re having trouble querying a document by the value in an array element. I wrote the following minimal repro and was able to successfully query documents from a collection with a similar structure:

using MongoDB.Bson;
using MongoDB.Driver;

var client = new MongoClient();
var db = client.GetDatabase("test");
var coll = db.GetCollection<BsonDocument>("coll");

var filter = Builders<BsonDocument>.Filter.Eq("Parameters.Value", 11111);
var query = coll.Find(filter);
foreach (var result in query.ToList())
{
    Console.WriteLine(result);
}

Note that your C# filter contains the value "11111" (data type is string) but your schema appears to contain values in the array of type int. In my filter above, I use the numeric value 11111 to query matching documents.

When querying data from MongoDB, you must either use the correct data types in your query or explicitly convert values to a common data type prior to comparison.

If you continue to have problems with this query, please provide a self-contained repro as well as sample data so we can troubleshoot further.

Sincerely,
James

1 Like

Hey, @James_Kovacs

I’d like to thank you for taking the time to reply to me. Apparently there are sometimes string values for Value and other times there are integer values. I did however try your solution and it does not work, so I assume something else is wrong with my code.

I’ll be investigating a bit more before troubling anyone again, but I will definitely come back and give an update once I either give up investigating and seek more help, or figure out the solution to my issue for future reference.

Regardless, thank you very much!

1 Like

@James_Kovacs

I’ve actually found user-error in my code. I’m connecting and managing two databases simultaneosly and I was actually applying my queries to the other database which doesn’t even share the same structure.

Sorry for your time and thank you again.

1 Like

A post was split to a new topic: How can I filter entries based on the FieldValue.Alias and FieldValue.Value?