我有一个包含字符串数组字段AccountIds
的DTO。我想检查一个给定的字符串AccountId
是否包含在这个数组中。
我尝试使用ElemMatch
过滤器来实现这样:
var accountId = "04935ec9ecf94eb5b57ac9b2957bfb9a";
var filter = Builders<MapDto>.Filter.ElemMatch(x => x.AccountIds, accountId);
var result = await _collection.Find(filter).ToListAsync();
我的文档是这样的:
{
"_id" : ObjectId("62c1628a39094e414593c8c7"),
"AccountIds" : [
"04935ec9ecf94eb5b57ac9b2957bfb9a"
]
}
但是,抛出了以下异常,我不确定为什么:
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)
当你在数组中搜索单个条目时,你不需要使用elemMatch,你可以很容易地通过:
db.collection.find({"AccountIds":"04935ec9ecf94eb5b57ac9b2957bfb9a"})
或c#中的
Builders<MapDto>.Filter.Eq(x => x.AccountIds, accountId)
试试这个
var accountId = "04935ec9ecf94eb5b57ac9b2957bfb9a";
var filter = Builders<MapDto>.Filter.AnyEq(x => x.AccountIds, accountId);
var result = await _collection.Find(filter).ToListAsync();