I have a DTO that contains a string array field AccountIds
. I want to check if a given string AccountId
is contained within this array.
I tried using the ElemMatch
filter to achieve this like so:
var accountId = "04935ec9ecf94eb5b57ac9b2957bfb9a";
var filter = Builders<MapDto>.Filter.ElemMatch(x => x.AccountIds, accountId);
var result = await _collection.Find(filter).ToListAsync();
This is how my document looks like:
{
"_id" : ObjectId("62c1628a39094e414593c8c7"),
"AccountIds" : [
"04935ec9ecf94eb5b57ac9b2957bfb9a"
]
}
However, the following exception is thrown, and I’m not sure why.
System.FormatException: Invalid JSON number '04'.
at MongoDB.Bson.IO.JsonScanner.GetNumberToken(JsonBuffer buffer, Int32 firstChar)
at MongoDB.Bson.IO.JsonScanner.GetNextToken(JsonBuffer buffer)
at MongoDB.Bson.IO.JsonReader.PopToken()
at MongoDB.Bson.IO.JsonReader.ReadBsonType()
at MongoDB.Bson.IO.BsonReader.GetCurrentBsonType()
at MongoDB.Bson.Serialization.Serializers.SerializerBase`1.EnsureBsonTypeEquals(IBsonReader reader, BsonType bsonType)
at MongoDB.Bson.Serialization.Serializers.BsonValueSerializerBase`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)
at MongoDB.Bson.BsonDocument.Parse(String json)
at MongoDB.Driver.JsonFilterDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.ElementMatchFilterDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.AndFilterDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
at MongoDB.Driver.MongoCollectionImpl`1.FindAsync[TProjection](IClientSessionHandle session, FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.<>c__DisplayClass47_0`1.<FindAsync>b__0(IClientSessionHandle session)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
2
Answers
You dont need to use elemMatch when you search for single entry in array , you can do easily via:
or in C#:
Try this instead.