我正在尝试通过
ElemMatch
搜索时间间隔。我感兴趣的领域包括简单的对象或对象数组,如下所示:
{
"ID": "123456789",
"field1": {
"item1": "string",
"item2": 123
},
"field2": [
{
"item11": 11.11,
"myDatetime": {
ts: 2022-10-23T23:14:55
}
},
{
"item11": 12.22,
"myDatetime": {
ts: 2022-08-23T23:14:55
}
}
]
}
我的模型是:
public record MongoCollection
{
public string ID { get; init; }
public object field1 { get; init; }
public List<object> field2 { get; init; }
}
我正在尝试以这种方式实现
ElemMatch
:
var filter = Builders<MongoCollection>.Filter.ElemMatch("field1",
Builders<MongoCollection>.Filter.And(
Builders<MongoCollection>.Filter.Gte("myDatetime.ts", fromDate),
Builders<MongoCollection>.Filter.Lte("myDatetime.ts", tillDate))
);
我在这部分代码中收到的错误是:
无法将“MongoDB.Bson.Serialization.Serializers.ObjectSerializer”类型的对象转换为类型“MongoDB.Bson.Serialization.IBsonSerializer”
我也试过这个方法:
var field = new StringFieldDefinition<MongoCollection, List<object>>("field1");
和
FieldDefinition<MongoCollection,List<object>> field = "field1";
我把
field
放在ElemMatch
里,像这样:
var filter = Builders<MongoCollection>.Filter.ElemMatch(field,
Builders<MongoCollection>.Filter.And(
Builders<MongoCollection>.Filter.Gte("myDatetime.ts", fromDate),
Builders<MongoCollection>.Filter.Lte("myDatetime.ts", tillDate))
);
我收到了同样的错误。 我该如何解决?
你应该参考
field2
而不是field1
。
因为在
MongoCollection
类中,field2
中的项目是object
类型,嵌套对象的过滤器应该是object
类型,使用Builders<object>
。
var filter = Builders<MongoCollection>.Filter.ElemMatch("field2",
Builders<object>.Filter.And(
Builders<object>.Filter.Gte("myDatetime.ts", fromDate),
Builders<object>.Filter.Lte("myDatetime.ts", tillDate))
);