c# - 如何使用 C# 过滤 MongoDB 数组以仅返回我需要的特定记录
问题描述
我的查询。
public List<T> GetETrannsfer<T>(string table, string Branch, string userName, string status)
{
var collection = db.GetCollection<T>(table);
var filter = Builders<T>.Filter.And(Builders<T>.Filter.Regex("Branch", new BsonRegularExpression("/^" + Branch + "$/i")),
Builders<T>.Filter.Eq("eLogInfo.userName", userName),
Builders<T>.Filter.Eq("eLogInfo.status", status));
return collection.Find(filter).ToList();
}
我的设备LogModel
[BsonIgnoreExtraElements]
public class EquipmentLogModel
{
[BsonId]
public ObjectId _id { get; set; }
public string eLogType { get; set; }
public string Branch { get; set; }
public EquipmentLogInfoModel[] eLogInfo { get; set; }
}
[BsonIgnoreExtraElements]
public class EquipmentLogInfoModel
{
[BsonId]
public ObjectId _id { get; set; }
public string userName { get; set; }
public string eModel { get; set; }
public string comments { get; set; }
public string eDescription { get; set; }
public string serialNum { get; set; }
public string status { get; set; }
}
如果数组中的一个对象包含过滤后的变量,MongoDB 会向我发送数组中所有对象的结果。我只需要包含特定变量的对象。
所以我尝试按照建议使用 ElemMatch 我仍然得到相同的结果记录没有被过滤结果包含特定数组下的所有记录。
public EquipmentLogModel GetETrannsfer(string table, string Branch, string userName, string status)
{
var collection = db.GetCollection<EquipmentLogModel>(table);
var filter = Builders<EquipmentLogModel>.Filter.And(Builders<EquipmentLogModel>.Filter.Regex("Branch", new BsonRegularExpression("/^" + Branch + "$/i")),
Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.status == status),
Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.userName == userName));
return collection.Find(filter).First();
}
我也尝试了以下方法,它只返回了一条我需要不止一条的记录,并且我无法通过多个变量过滤返回。
public EquipmentLogInfoModel GetETrannsfer(string table, string Branch, string userName, string status)
{
var filter = Builders<EquipmentLogModel>.Filter.And(Builders<EquipmentLogModel>.Filter.Regex("Branch", new BsonRegularExpression("/^" + Branch + "$/i")),
Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.status == status),
Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.userName == userName));
var collection = db.GetCollection<EquipmentLogModel>(table).Find(filter)
.FirstOrDefault();
return collection.eLogInfo.FirstOrDefault(a => a.userName == userName);
}
解决方案
推荐阅读
- java - 使用 JUnit/Mockito 确认 java.util.Timer.schedule() 是否符合预期?
- avaudioengine - AVAudioEngine 文档
- c# - 在 Swagger 上为 .net Web api 调用添加自定义标头字段的最佳实践是什么?
- database - 通过数据库自动更新网站
- java - Intent 数据到另一个 Activity 时的异常 android.content.Context.getPackageName()
- python - 在python中计算NxN矩阵的熵
- windows - Apache webdav 登录适用于浏览器,但 net use 命令/窗口资源管理器出错
- javascript - javascript中1到100个随机10个数字的最佳方法没有欺骗?
- nginx - Nginx block all traffic except URL with specific format
- django - 唯一约束失败:accounts_user.username