I want to find documents using the elementMatch operator (or something that works better).
Example:
{
"_id": "1",
"messages": [
"foo A",
"bar B"
]
},
{
"_id": "2",
"messages": [
"bar B"
]
}
I want to find all documents where the string foo
is contained in any string in the messages
array.
I am trying to make the syntax work using the BsonDocument
syntax in C#. I do not have C# models, only BsonDocument/BsonValue.
Something like:
var Filter = Builders<BsonDocument>.Filter;
var ItemFilter = Builders<BsonValue>.Filter;
var result = await collection.FindAsync(FindFilter.ElemMatch<BsonValue>("messages", ItemFilter.???));
How would this work? Given the documents above, this should return the first document with id=1, because its messages array contains at least one string that contains "foo".
Thanks for helping out.
As long as messages
is a array of simple strings and there is only one condition, you do not need to use the $elemMatch
filter. A simple Regex condition can be applied and will return all documents, that have at least one array item that matches the regex:
var filter = Builders<BsonDocument>.Filter.Regex("messages",
new BsonRegularExpression("foo"));
Alternatively, you can also use a System.Text.RegularExpressions.Regex
:
var filter = Builders<BsonDocument>.Filter.Regex("messages", new Regex("foo"));
Above sample returns the document with id _id == 1
.
As you need to find items that contain the text "foo", at the time of this writing there is no way to express this using the driver syntax. ElemMatch
is used for arrays with subdocuments and while there are Any*
methods, that can be used with arrays of scalar values, there is no AnyRegex
method that would lead to the corresponding MQL query.